I'm new to Spring:
I do not want authenticated user from accessing the login page. What is the proper way to handle redirects for the '/login' if the user is already authenticated? Say, I want to redirect to '/index' if already logged in.
I have tried 'isAnonomous()' on login, but it redirects to access denied page.
<security:http auto-config="true" use-expressions="true" ...> <form-login login-processing-url="/resources/j_spring_security_check" default-target-url="/index" login-page="/login" authentication-failure-url="/login?login_error=t" /> <logout logout-url="/resources/j_spring_security_logout" /> ... <security:intercept-url pattern="/login" access="permitAll" /> <security:intercept-url pattern="/**" access="isAuthenticated()" /> </security:http>
Another way to redirect users is through an interceptor on the URI of the login page. The interceptor will intercept the request before it arrives at the controller. Therefore, we can decide based on the authentication if we let it go further or we block it and return a redirect response.
Try a URL http://localhost:8080/HelloWeb/index and you should see the following result if everything is fine with your Spring Web Application. Click the "Redirect Page" button to submit the form and to get the final redirected page.
In the controller function of your login page:
check if a user is logged in.
then forward/redirect him to the index page in that case.
Relevant code:
Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!(auth instanceof AnonymousAuthenticationToken)) { /* The user is logged in :) */ return new ModelAndView("forward:/index"); }
Or in another scenario where the mapping may be containing path variable
like @GetMapping(path = "/user/{id}")
in this case you can implement this logic as well:
@GetMapping(value = "/login") public String getLogin() throws Exception { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!(auth instanceof AnonymousAuthenticationToken)) { User loggedInUser = userService.findByEmail(auth.getName()) .orElseThrow(Exception::new); /* The user is logged in :) */ return "redirect:/user/" + loggedInUser.getUserId(); } return "login"; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With