How to redirect to the homepage if the user accesses the login page after being logged in?

后端 未结 6 1324
一生所求
一生所求 2020-11-28 13:16

Here is my spring security config:




        
6条回答
  •  Happy的楠姐
    2020-11-28 14:21

    I've checked the topic more deeply than last time and found that you have to determine if user is authenticated by yourself in controller. Row Winch (Spring Security dev) says here:

    Spring Security is not aware of the internals of your application (i.e. if you want to make your login page flex based upon if the user is logged in or not). To show your home page when the login page is requested and the user is logged in use the SecurityContextHolder in the login page (or its controller) and redirect or forward the user to the home page.

    So solution would be determining if user requesting /auth/login is anonymous or not, something like below.

    applicationContext-security.xml:

    
        
        
        
        
    
        
        
    
    
    
        
    
    
    
    
    
        
    
    

    Add to applicationContext.xml bean definition:

    
    

    which is class

    public final class SecurityContextAccessorImpl
          implements SecurityContextAccessor {
    
      @Autowired
      private AuthenticationTrustResolver authenticationTrustResolver;
    
      @Override
      public boolean isCurrentAuthenticationAnonymous() {
        final Authentication authentication =
            SecurityContextHolder.getContext().getAuthentication();
        return authenticationTrustResolver.isAnonymous(authentication);
      }
    }
    

    implementing simple interface

    public interface SecurityContextAccessor {
      boolean isCurrentAuthenticationAnonymous();
    }
    

    (SecurityContextHolder accessing code is decoupled from controller, I followed suggestion from this answer, hence SecurityContextAccessor interface.)

    And last but not least redirect logic in controller:

    @Controller
    @RequestMapping("/auth")
    public class AuthController {
      @Autowired
      SecurityContextAccessor securityContextAccessor;
    
      @Autowired
      @Qualifier("defaultTargetUrl")
      private String defaultTargetUrl;
    
      @RequestMapping(value = "/login", method = RequestMethod.GET)
      public String login() {
        if (securityContextAccessor.isCurrentAuthenticationAnonymous()) {
          return "login";
        } else {
          return "redirect:" + defaultTargetUrl;
        }
      }
    }
    

    Defining defaultTargetUrl String bean seems like a hack, but I don't have better way not to hardcode url... (Actually in our project we use with class containing static final String fields.) But it works after all.

提交回复
热议问题