spring-Security(三):记住我,实现下次免登录

记住我基本原理

  1. 用户认证成功之后调用RemeberMeService根据用户名名生成TokenTokenRepository写入到数据库,同时也将Token写入到浏览器的Cookie
  2. 重启服务之后,用户再次登入系统会由RememberMeAuthenticationFilter拦截,从Cookie中读取Token信息,与persistent_logins表匹配判断是否使用记住我功能。最中由UserDetailsService查询用户信息

具体实现:

步骤一:

创建persistent_logins

create table persistent_logins (username varchar(64) not null, series varchar(64) primary key, token varchar(64) not null, last_used timestamp not null);

这个表是统一的,springsecrity会自动在这个表保存和读取token信息

步骤二:

登陆页面添加记住我复选款(name必须是remeber-me)

<input name="remember-me" type="checkbox"> 下次自动登录

步骤三:配置WebSecurityConfig

1.加入下面的代码,springSecurity会根据情况自动将token插入persistent_logins表和和从persistent_logins表读取token

 @Autowired
    private DataSource dataSource;
    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource);
        return tokenRepository;
    }
2.设置httpSecurity
 protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/user/**").hasRole("USER")
                .antMatchers("/ws").hasRole("USER")
                .and()
                .formLogin().loginPage("/login").defaultSuccessUrl("/ws")
                .and()
                .logout().logoutUrl("/logout").logoutSuccessUrl("/login")

                //记住我开始,场景:有这样一个场景——有个用户初访并登录了你的网站,
                // 然而第二天他又来了,却必须再次登录。于是就有了“记住我”这样的功能来方便用户使用
                .and()
                .rememberMe()
                .tokenRepository(persistentTokenRepository())//设置操作表的Repository
                .tokenValiditySeconds(60 * 60 * 24 * 7)//设置记住我的时间为7天
                .userDetailsService(myUserDetailsService);//设置userDetailsService
                //记住我结束
        
        // 加http.csrf().disable()是为了防止报这个错Whitelabel Error Page
       //This application has no explicit mapping for /error, so you are seeing this as a fallback.
        http.csrf().disable();

    }

猜你喜欢

转载自blog.csdn.net/liyu121/article/details/80293369