RememberMe功能
rememberMeServices接口
有AbstractRememberMeServices抽象类
- PersistentTokenBasedRememberMeServices实现类
- TokenBasedRememberMeServices
通过授权验证登录成功,到那时表单添加rememberme功能后,表单数据提交多了一项数据,loginsuccess判断值为true或者false,true会调用onLoginsuccess方法进行持久化存储
持久化存储有两种情况:
- 内存
- 数据库
内存PersistentTokenRepository接口的实现InMemoryTokenRepositoryImpl
数据库JdbcTokenRepositoryImpl实现进行持久化存储
Spring使用
<security:http auto-config="true" use-expressions="true">
<security:intercept-url pattern="/**" access="hasAnyRole('ROLE_ADMIN')"></security:intercept-url>
<security:form-login login-processing-url="/index"></security:form-login>
//rememberme功能添加,user-service自定义的userDetail的类的javaBean 后面就是数据库的javaBean
<security:remember-me user-service-ref="userDetail" data-source-ref="dataSource"></security:remember-me>
</security:http>
<security:authentication-manager>
<security:authentication-provider user-service-ref="userDetail">
</security:authentication-provider>
</security:authentication-manager>
直接起飞,但是需要在数据库中创建一个表
create table PERSISTENT_LOGINS (
USERNAME VARCHAR2(64),
SERIES VARCHAR2(64) not null,
TOKEN VARCHAR2(64),
LAST_USED TIMESTAMP,
constraint PK_PERSISTENT_LOGINS primary key (SERIES)
);
SpringBoot使用
@EnableWebSecurity
@Configuration
public class Security extends WebSecurityConfigurerAdapter {
@Autowired
private SecuritySer ss;
@Autowired
private DataSource ds;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**")
.hasAnyRole("ADMIN")
.anyRequest()
.permitAll()
.and()
.formLogin()
.permitAll()
.and()
.rememberMe()
.tokenRepository(setJdbc())
.tokenValiditySeconds(10000);
}
// 需要一个JdbcTokenRepositoryImpl对象,默认是使用的内存RememberMe实现,通过配置类切换即可
@Bean
public JdbcTokenRepositoryImpl setJdbc(){
JdbcTokenRepositoryImpl setToken = new JdbcTokenRepositoryImpl();
setToken.setDataSource(ds);
return setToken;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(ss);
}
}
以上仅为个人总结,如有不足或错误,请指正谢谢!