如果会话被删除,remember-me cookie 也会被删除

if session deleted, remember-me cookie is also deleted

我正在学习 Spring 安全。 我有一个关于记住我功能的问题。

这是我的部分来源。

如果我关闭浏览器并打开新浏览器,会话cookie 的值是相同的。 如果我使用 logout(.deleteCookies("JSESSIONID")) 删除会话 cookie,记住我的 cookie 也会被删除。

下面我需要,

如果关闭一个浏览器并打开一个新浏览器,会话cookie的值是不同的。 如果使用注销删除会话 cookie,则保留记住我的 cookie。

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    AuthenticationService authenticationService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
                .antMatchers("/resource/**", "/login", "/login-error").permitAll()

                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/user/**").hasRole("USER")

                .anyRequest().authenticated()
                .and()
            .formLogin()
                .failureUrl("/login?error")
                .defaultSuccessUrl("/main", true)
                .permitAll()
                .and()
            .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login?logout")
                .deleteCookies("JSESSIONID")
                .permitAll()
                .and()
            .rememberMe()
                .rememberMeParameter("remember-me")
                .tokenValiditySeconds(60*2)
                .tokenRepository(persistentTokenRepository());

        http
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.NEVER);
        http
            .exceptionHandling()
                .accessDeniedPage("/login?error");
        http
            .sessionManagement()
                .invalidSessionUrl("/login");
    }

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl db = new JdbcTokenRepositoryImpl();
        db.setDataSource(dataSource);
        return db;
    }


    ... (other source)

如果您使用流利 API,默认情况下您的记住我 cookie 会被删除,请参阅 Spring Security Reference

10.24.1 Logout Java Configuration

When using the WebSecurityConfigurerAdapter, logout capabilities are automatically applied. The default is that accessing the URL /logout will log the user out by:

  • Invalidating the HTTP Session
  • Cleaning up any RememberMe authentication that was configured
  • Clearing the SecurityContextHolder
  • Redirect to /login?logout

但看起来您可以使用自己的 RememberMeServices, see Spring Security Reference:

实现来做到这一点

services-ref Allows complete control of the RememberMeServices implementation that will be used by the filter. The value should be the id of a bean in the application context which implements this interface. Should also implement LogoutHandler if a logout filter is in use.