How i can redirect after my loginPost method with header Authorization(my jquery code):
$(document).ready(function (){
$("#form-login").submit(function (event){
event.preventDefault();
let $form = $(this),
email = $form.find("input[name='email'").val(),
password = $form.find("input[name='password'").val();
loginPost(email, password);
})
function loginPost(email, password) {
$.ajax({
url:"/api/auth/login",
type:"POST",
async:false,
data: {email, password},
success: function (data) {
let urlLogin;
if(data["role"] === "ROLE_USER") {
urlLogin = "/api/user"
} else {
urlLogin = "/api/admin"
}
$.ajax({
url:urlLogin,
type:"GET",
async: false,
headers: {
"Authorization": "Bearer " data["token"]
}
})
}
})
}
Thymeleaf ViewController :
@Controller
@RequestMapping("/api")
public class ViewController {
@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping("/user")
public String userPage() {
return "user_page";
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping("/admin")
public String adminPage() {
return "admin_page";
}
}
After get request i have only response with hmtl page, but i need to redirect get route with rendering this page. If i doing window.location="/api/user" i have response 401.
CodePudding user response:
In javascript you can change the page via
window.location.href = "http://www.example.com";
. In your case I would suggest you to do something like window.location.href = "http://www.yoururl.com" urlLogin;
or something like this. If you want to redirect using just the php (on server side) you can do this by setting the Location
header.
You can set the Location header by doing this:
$path = "/admin";
header("Location: " . $path);
or header("Location: /admin");
Have a nice day!