2016-12-27 53 views
1

我正在使用Spring Boot 1.4.2(使用嵌入式Tomcat),Spring MVC 4.3.4和Spring Security 4.1.3構建一個簡單的網站。我的登錄頁面包含一個記住我的複選框,它可以切換是否記住我的Cookie是由Spring Security創建的。爲Spring Security添加過期記住我的Cookie

此cookie在Chrome和Firefox中設置得非常好,但由於IE和MS Edge不使用Max-Age屬性,因此只能創建會話Cookie。有沒有辦法讓Spring Security(Max-Age的屬性)在Set-Cookie標題中爲記住我的cookie設置?

下面是我的春節,安全配置:

http.authorizeRequests() 
      .antMatchers("/admin/**").hasRole("ADMIN") 
      .antMatchers("/private/**").authenticated() 
      .anyRequest().permitAll() 
      .and() 
     .httpBasic() 
      .and() 
     .formLogin() 
      .loginPage("/login").permitAll().and() 
     .rememberMe() 
      .tokenValiditySeconds(365 * 24 * 60 * 60) 
      .and() 
     .sessionManagement() 
      .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED); 

回答

1

附加Max-Age你也可以添加Expires屬性。

的配置是容器的一部分,看到Apache Tomcat 8 Configuration Reference

alwaysAddExpires

If this is true Tomcat will always add an expires parameter to a SetCookie header even for cookies with version greater than zero. This is to work around a known IE6 and IE7 bug that causes I to ignore the Max-Age parameter in a SetCookie header.

If org.apache.catalina.STRICT_SERVLET_COMPLIANCE is set to true, the default of this setting will be false, else the default value will be true.

但是沒有Common application properties在春季啓動Expires。因此,您必須將CookieProcessor更改爲LegacyCookieProcessor並進行配置,請參閱Spring Boot Reference Guide

70.10 Use Tomcat’s LegacyCookieProcessor

The embedded Tomcat used by Spring Boot does not support "Version 0" of the Cookie format out of the box, and you may see the following error:

java.lang.IllegalArgumentException: An invalid character [32] was present in the Cookie value 

If at all possible, you should consider updating your code to only store values compliant with later Cookie specifications. If, however, you’re unable to change the way that cookies are written, you can instead configure Tomcat to use a LegacyCookieProcessor . To switch to the LegacyCookieProcessor use an EmbeddedServletContainerCustomizer bean that adds a TomcatContextCustomizer :

@Bean 
public EmbeddedServletContainerCustomizer cookieProcessorCustomizer() { 
    return new EmbeddedServletContainerCustomizer() { 

     @Override 
     public void customize(ConfigurableEmbeddedServletContainer container) { 
      if (container instanceof TomcatEmbeddedServletContainerFactory) { 
       ((TomcatEmbeddedServletContainerFactory) container) 
         .addContextCustomizers(new TomcatContextCustomizer() { 

        @Override 
        public void customize(Context context) { 
         context.setCookieProcessor(new LegacyCookieProcessor()); 
        } 

       }); 
      } 
     } 
    }; 
}