前言
实现“记住我”功能,在用户登录一次以后,系统会记住用户一段时间,在这段时间,用户不用反复登录就可以使用系统。
代码改动
1. 前端改动
<input name="remember-me" type="checkbox"> 自动登录
2. 创建persistent_logins表
CREATE TABLE `persistent_logins` ( `username` varchar(64) NOT NULL, `series` varchar(64) NOT NULL, `token` varchar(64) NOT NULL, `last_used` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`series`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3. 配置WebSecurityConfig
WebSecurityConfig 中注入 dataSource
,创建一个 PersistentTokenRepository
的Bean:
@Autowired private DataSource dataSource; @Bean public PersistentTokenRepository persistentTokenRepository(){ JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl(); tokenRepository.setDataSource(dataSource); // 如果token表不存在,使用下面语句可以初始化该表;若存在,请注释掉这条语句,否则会报错。 // tokenRepository.setCreateTableOnStartup(true); return tokenRepository; }
在config(HttpSecurity http)
中按如下所示配置自动登陆:
@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() // 如果有允许匿名的url,填在下面 // .antMatchers().permitAll() .anyRequest().authenticated() .and() // 设置登陆页 .formLogin().loginPage("/login") // 设置登陆成功页 .defaultSuccessUrl("/").permitAll() // 自定义登陆用户名和密码参数,默认为username和password // .usernameParameter("username") // .passwordParameter("password") .and() .logout().permitAll() // 自动登录 .and().rememberMe() .tokenRepository(persistentTokenRepository()) // 有效时间:单位s .tokenValiditySeconds(60) .userDetailsService(userDetailsService); // 关闭CSRF跨域 http.csrf().disable(); }
运行程序
勾选自动登录后,浏览器Cookie和数据库中均存储了token信息
重启服务,直接访问成功登录之后的页面,即可直接登录。
注意:浏览器中的cookies信息不能清空,清空便获取不了cookies这个token,就不能通过token查询数据库来获取用户信息,最后不能自动登录。