- 用户选择了“记住我”成功登录后,将会把username、随机生成的序列号、生成的token存入一个数据库表中,同时将它们的组合生成一个cookie发送给客户端浏览器。
- 当没有登录的用户访问系统时,首先检查 remember-me 的 cookie 值 ,有则检查其值包含的 username、序列号和 token 与数据库中是否一致,一致则通过验证。并且系统还会重新生成一个新的 token 替换数据库中对应旧的 token,序列号 series 保持不变 ,同时删除旧的 cookie,重新生成 cookie 值(新的 token + 旧的序列号 + username)发送给客户端。
- 如果对应cookie不存在,或者包含的username、序列号和token 与数据库中保存的不一致,那么将会引导用户到登录页面。
- 因为cookie被盗用后还可以在用户下一次登录前顺利的进行登录,所以如果你的应用对安全性要求比较高就不要使用Remember-Me功能。
记住我需要数据库支持,因此引入如下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
application.yml中配置数据源
spring:
thymeleaf:
cache: false #关闭thymeleaf缓存
prefix: classpath:/templates/
suffix: .html
datasource:
username: root
password: 密码
url: jdbc:mysql://ip:3306/study-security?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC&nullCatalogMeansCurrent=true
driver-class-name: com.mysql.cj.jdbc.Driver
# 数据源其他配置, 在 DruidConfig配置类中手动绑定
initialSize: 8
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
配置类中设置数据源给JdbcTokenRepositoryImpl
//============================== 记住我 Spring Security实现了该功能 ====================
/**
* 1. jdbcTokenRepository()
* 2. configure(HttpSecurity http)中配置
* 3. 页面 <input name="remember-me" type="checkbox" id="remember"> 中 name="remember-me"是固定的
* <p>
* <p>
* Cookie: JSESSIONID=4ABC0F22FFB87F68228A5409646E0429; remember-me=RzNuT2puTUhPSW9LMVRUcTJScG43dyUzRCUzRDpCYko4QU42aEZpS0NHUzRES09WMXZRJTNEJTNE
*/
@Autowired
private DataSource dataSource;
@Bean
public JdbcTokenRepositoryImpl jdbcTokenRepository() {
final JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
//jdbcTokenRepository.setCreateTableOnStartup(true); //自动创建表,第二次会报错
return jdbcTokenRepository;
}
//========================================================================================
org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl
中定义有sql
/** Default SQL for creating the database table to store the tokens */
public static final String CREATE_TABLE_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)";
配置类中添加记住我
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/login/page")
.loginProcessingUrl("/login")
.and()
.authorizeRequests()
.antMatchers("/login/page").permitAll()
.anyRequest().authenticated()
.and()
.rememberMe() //记住我功能
.tokenRepository(jdbcTokenRepository()) //保存登录信息
.tokenValiditySeconds(60 * 60 * 24 * 7); //记住我有效时长;
http.csrf().disable();
}
页面添加<input name="remember-me" type="checkbox" id="remember">
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>自定义登录页面</title>
</head>
<body>
<form action="/login" method="POST">
用户名:<input name="username" type="text"><br/>
密码:<input name="password" type="password"><br/>
<!-- remember-me 不能修改 -->
记住我:<input name="remember-me" type="checkbox" id="remember"><br/>
<button type="submit" >登录</button>
</form>
</body>
</html>
http://localhost:8080/hello
打开浏览器控制台,点击登录
数据库