Log user in with remember-me functionality in Spring 3.1

后端 未结 2 778
南方客
南方客 2020-12-13 11:04

I currently log users in programmatically (like when they login through Facebook or other means than using my login form) with:

SecurityContextHolder.getCont         


        
2条回答
  •  南方客
    南方客 (楼主)
    2020-12-13 11:14

    I assume you already have set in your configuration.

    The way remember-me works is it sets a cookie that is recognized when the user comes back to the site after their session has expired.

    You'll have to subclass the RememberMeServices (TokenBased or PersistentTokenBased) you are using and make the onLoginSuccess() public. For example:

    public class MyTokenBasedRememberMeServices extends PersistentTokenBasedRememberMeServices {
        @Override
        public void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) {
            super.onLoginSuccess(request, response, successfulAuthentication);
        }   
    } 
    
    
    
    
        
        
    
    

    Inject your RememberMeServices into the bean where you are doing the programmatic login. Then call onLoginSuccess() on it, using the UsernamePasswordAuthenticationToken that you created. That will set the cookie.

    UsernamePasswordAuthenticationToken auth = 
        new UsernamePasswordAuthenticationToken(user, "", authorities);
    SecurityContextHolder.getContext().setAuthentication(auth);
    getRememberMeServices().onLoginSuccess(request, response, auth);  
    

    UPDATE

    @at improved upon this, with no subclassing of RememberMeServices:

    UsernamePasswordAuthenticationToken auth = 
        new UsernamePasswordAuthenticationToken(user, "", authorities);
    SecurityContextHolder.getContext().setAuthentication(auth);
    
    // This wrapper is important, it causes the RememberMeService to see
    // "true" for the "_spring_security_remember_me" parameter.
    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) {
        @Override public String getParameter(String name) { return "true"; }            
    };
    
    getRememberMeServices().loginSuccess(wrapper, response, auth);  
    

提交回复
热议问题