Spring-security: помните, что мой токен работает только один раз

У меня действительно странная проблема с Spring Security.

Токен «запомнить меня», похоже, действует только для одного автоматического входа в систему, после чего он перестает работать.

1. После входа:

введите описание изображения здесь

2. Затем я вручную удаляю файл cookie JSESSIONID и перезагружаю страницу

введите описание изображения здесь

3. Я снова удаляю файл cookie JSESSIONID и снова перезагружаю страницу.

Теперь я вышел из системы!

В консоли получаю следующее:

SEVERE [http-nio-8080-exec-10] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [dispatcher] in context with path [] threw exception
 org.springframework.security.web.authentication.rememberme.CookieTheftException: Invalid remember-me token (Series/token) mismatch. Implies previous cookie theft attack.

Я читал, что это может быть результатом того, что браузер выдает несколько запросов одновременно, я проверил (отключил все ресурсы, оставив только обычный HTML, но безрезультатно)

введите описание изображения здесь

Вот моя конфигурация

@EnableWebSecurity
public class Security extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Autowired
    DataSource dataSource;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/assets/**").permitAll();
        http.authorizeRequests().anyRequest().authenticated();

        http.formLogin().permitAll();    
        http.rememberMe().tokenRepository(persistentTokenRepository()).userDetailsService(customUserDetailsService);

        http.logout().permitAll();
    }

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

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider());
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(customUserDetailsService);
        authProvider.setPasswordEncoder(passwordEncoder());
        return authProvider;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(11);
    }
}

person guidev    schedule 12.04.2018    source источник


Ответы (1)


У меня сработало извлечение источника данных из конфига, попробуйте

@Autowired
JpaConfiguration jpaConfig;

@Bean(name = "persistentTokenRepository")
public PersistentTokenRepository persistentTokenRepository() {
    JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
    tokenRepository.setDataSource(jpaConfig.dataSource());
    return tokenRepository;
}

или вы также можете попробовать увеличить срок действия токена

 @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/assets/**").permitAll();
        http.authorizeRequests().anyRequest().authenticated();

        http.formLogin().permitAll();    
        http.rememberMe().tokenRepository(persistentTokenRepository()).userDetailsService(customUserDetailsService)
            .tokenValiditySeconds(1209600);

        http.logout().permitAll();
    }
person UsamaAmjad    schedule 21.04.2018