Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security - Redirect if already logged in

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> 
like image 680
steve Avatar asked Oct 29 '12 23:10

steve


People also ask

How do I redirect a spring security login page?

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.

How do I redirect a page in spring?

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.


1 Answers

In the controller function of your login page:

  1. check if a user is logged in.

  2. 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"); } 

Update

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"; } 
like image 61
Rahul Avatar answered Sep 23 '22 15:09

Rahul