Romanov1981
@Romanov1981

Почему при использовании rememberMe в Sprung Security происходит зацикливание?

Приветствую уважаемые форумчану.

Подскажите пожалуйста, почему при использовании rememberMe в Sprung Security происходит зацикливание?

Например: очищаю Cookies, захожу на сайт, авторизовываюсь, но при этом ставлю галочку "запомнить меня". Всё нормально.

Далее, не выходя из системы, если перезагрузить сервер то вроде всё нормально, я остаюсь авторизованным, но если попробовать попасть на страницу входа, то страница начинает зависать, система начинает зацикливаться на подключении к БД

Hibernate: 
    select
        user0_.username as col_0_0_,
        user0_.password as col_1_0_ 
    from
        User user0_ 
    where
        user0_.username=?
Hibernate: 
    select
        user0_.username as col_0_0_,
        user0_.password as col_1_0_ 
    from
        User user0_ 
    where
        user0_.username=?
Hibernate: 
    select
        user0_.username as col_0_0_,
        user0_.password as col_1_0_ 
    from
        User user0_ 
    where
        user0_.username=?


а если остановить и перезагрузить страницу то появляется Exeption - Message Invalid remember-me token (Series/token) mismatch. Implies previous cookie theft attack.

и если ещё раз перезагрузить, то всё становится нормально, но только что бы войти, нужно заново авторизоваться.

Вот такая беда, почему такая беда не знаю.

На всякий случай сделал тестовый TestRemember https://github.com/romanych2021/TestRemember

Помогите решить проблему? Ведь не здоровая эту штука.

SecurityConfig

package com.testremember.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    private final
    PersistentTokenRepository persistentTokenRepository;

    private final
    UserDetailsService userDetailsService;

    public SecurityConfig(PersistentTokenRepository persistentTokenRepository, UserDetailsService userDetailsService) {
        this.persistentTokenRepository = persistentTokenRepository;
        this.userDetailsService = userDetailsService;
    }



    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService);
    }



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

                .mvcMatchers("/").permitAll()
                .mvcMatchers("/login", "/registration").anonymous()
                .mvcMatchers("/admin").hasAnyRole("ADMIN")
                .mvcMatchers("/user").hasAnyRole("ADMIN", "USER")

                .and()
                .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/login")
                .defaultSuccessUrl("/")

                .and().csrf().disable()
                .rememberMe()
                .tokenRepository(persistentTokenRepository)
                .rememberMeParameter("remember-me")
                .rememberMeCookieName("_rm")

                .and()
                .logout()
                .permitAll()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/")

                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID");

    }


}


UserDetail

package com.testremember.security;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Collections;

@Service
public class UserDetail implements UserDetailsService {





    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        return new org.springframework.security.core.userdetails.User("user", "{noop}1111",
                true, true, true, true, getAuthorities());

    }


    private Collection<? extends GrantedAuthority> getAuthorities(){

        return Collections.singletonList(new SimpleGrantedAuthority("ROLE_ADMIN"));

    }




}
  • Вопрос задан
  • 133 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы