实现Remember me功能;
1、创建临时登录的数据库
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;
2、进行配置,首先需要配置数据源,在之前整合Mybatisplus已经配置了数据源,所以这边只需要进行注入。还需要注入操作数据库的方式,这边采用的是JdbcTokenRepositoryImpl;
@Autowired
private DataSource dataSource;
@Autowired
private PersistentTokenRepository tokenRepository;
@Bean
public PersistentTokenRepository persistentTokenRepository(){
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
// 赋值数据源
jdbcTokenRepository.setDataSource(dataSource);
// 自动创建表,第一次执行会创建,以后要执行就要删除掉!
// jdbcTokenRepository.setCreateTableOnStartup(true);
return jdbcTokenRepository;
}
3、配置remember-on生效,设置cookie时长,以及二次登录成功直接使用userDetailsService进行登录;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling().accessDeniedPage("/unauth.html");
// 配置认证
http.formLogin() //自定义自己编写的登录页面
.loginPage("/login.html") // 配置哪个 url 为登录页面
.loginProcessingUrl("/user/login") // 登录访问路径。
.defaultSuccessUrl("/success.html").permitAll()//登陆成功之后跳转地址
.and().authorizeRequests()
// .antMatchers("/","/test/hello","/user/login").permitAll()
// .antMatchers("/test/index").hasAuthority("admin")
// .antMatchers("/test/index").hasAnyAuthority("admin,manager")
// .antMatchers("/test/index").hasRole("sale1")
.anyRequest().authenticated()
.and().rememberMe().tokenRepository(tokenRepository)
.tokenValiditySeconds(6000)
.userDetailsService(userDetailsService)
.and().csrf().disable();// 关闭 csrf保护功能
}
4、如果出现以下的错误,很有可能是配置出错了
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name ‘springSecurityFilterChain’ defined in class path resource
[org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]:
5、登录进行测试,这时候是无法成功的,观察浏览器没有发现remember me的cookie;原因是没有在前端进行设置
6、在表单中添加复选框,重新测试,可以看到remember me以及可以重复登录。
记住我:<input type="checkbox"name="remember-me"title="记住密码"/><br/