Java 如何在使用AuthenticationProvider登录时设置cookie过期时间
我正在使用自定义AuthenticationProvider进行身份验证:Java 如何在使用AuthenticationProvider登录时设置cookie过期时间,java,spring,spring-boot,spring-security,Java,Spring,Spring Boot,Spring Security,我正在使用自定义AuthenticationProvider进行身份验证: @Component public class AuthProvider implements AuthenticationProvider { @Override public UserData authenticate(Authentication authentication) throws AuthenticationException { return
@Component
public class AuthProvider implements AuthenticationProvider {
@Override
public UserData authenticate(Authentication authentication)
throws AuthenticationException {
return (UserData) authentication;
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UserData.class);
}
(UserData
扩展AbstractAuthenticationToken
)
当我这样做时,用户会得到一个JSESSIONID
,过期时间为-1(直到浏览器关闭)
如何使JSSessionID具有自定义的过期时间?如果用户处于活动状态,我还可以续订吗?身份验证提供程序由Spring Security管理,因此发送到servlet的cookie过期时间参数也可以与自定义身份验证提供程序一起使用 您需要设置
最大年龄:
server:
servlet:
session:
cookie:
max-age: 30m
您可以使用spring提供的记住我功能的概念,如下所示:
@Configuration
@EnableWebSecurity
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean("authenticationManager")
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user1").password("{noop}user1Pass").roles("USER")
.and()
.withUser("admin1").password("{noop}admin1Pass").roles("ADMIN");
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/anonymous*").anonymous()
.antMatchers("/login*").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/login")
.failureUrl("/login.html?error=true")
.and()
.logout().deleteCookies("JSESSIONID")
.and()
.rememberMe().key("uniqueAndSecret")
;
}
}
默认情况下,过期时间为2周,但您也可以使用tokenValiditySeconds进行配置。例如,您希望它在1天后过期,然后:
rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400)
让我知道这是否有帮助。试着参考一次文章,让我知道它是否有帮助。谢谢你的回答,我试过了,但如果coockie max age是-1,它没有任何作用。正如我在回答中详细说明的那样,我必须首先改变这一点。这篇文章非常完整,但缺少它最终工作的最大年龄配置。只是StackOverflow的一个提示:这种建议应该作为评论发布。非常感谢。
rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400)