Spring Security RememberMe Services with Session Cookie

后端 未结 2 1270
闹比i
闹比i 2021-02-06 10:41

I am using Spring Security\'s RememberMe Services to keep a user authenticated.

I would like to find a simple way to have the RememberMe cookie set as a session cookie

2条回答
  •  时光说笑
    2021-02-06 11:17

    Spring Security 3 does not offer configuration of how the cookie is generated. You have to override the default behaviour:

    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
    
    /** Cookie expires on session. */
     public class PersistentTokenBasedRememberMeServicesCustom extends
       PersistentTokenBasedRememberMeServices {
    
      /** only needed because super throws exception. */
      public PersistentTokenBasedRememberMeServicesCustom() throws Exception {
        super();
      }
    
      /** Copy of code of inherited class + setting cookieExpiration, */
      @Override
      protected void setCookie(String[] tokens, int maxAge,
          HttpServletRequest request, HttpServletResponse response) {
        String cookieValue = encodeCookie(tokens);
        Cookie cookie = new Cookie(getCookieName(), cookieValue);
        //cookie.setMaxAge(maxAge); 
        cookie.setPath("/");
        cookie.setSecure(false); // no getter available in super, so always false
    
        response.addCookie(cookie);
      }
    }
    

    Make sure, you use this customized PersistentTokenBasedRememberMeServices for you're rememberMeService by adding the class name to it's bean configuration:

    
    

提交回复
热议问题