Spring Security RememberMe

2018-09-24  本文已影响44人  司鑫

基本原理


rememberMe 流程 filter chains

UsernamePasswordAuthentication and BasicAthenticationFilter 无法校验时,RememberMeAuthenticationFilter 会进行校验请求中是否携带有 token,并进行下一步操作。

实现


@Configuration

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;
    @Autowired
    private CustomUserDetailsService customUserDetailsService;

   @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.rememberMe()
                .tokenRepository(persistentTokenRepository()) // 获取token
                .tokenValiditySeconds(3600)//token有效期
                .userDetailsService(customUserDetailsService); // 根据token拿到username后,从哪获取到用户信息
   }
    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource);
        tokenRepository.setCreateTableOnStartup(true);//在启动时,自动创建 token 表,或者自行执行SQL语句(create table persistent_logins (username varchar(64) not null, series varchar(64) primary key, "
            + "token varchar(64) not null, last_used timestamp not null)
        return tokenRepository;
     } 
}
上一篇下一篇

猜你喜欢

热点阅读