强迫学习的东西是不会保存在心里的。
—《柏拉图论教育》
实现“记住我”功能:
记住我基本原理
记住我功能具体实现
用户在登录以后,系统会记住此用户一段时间,在这段时间内用户不用反复登录就可以使用我们的系统。
当前面的Filter都没有办法认证用户信息时就会用RememberMeAuthenticationFilter尝试进行认证。
在登录页面添加记住我 选项,其中记住我的选择框必须是input checkbox类型的多选框,并且它的name必须是name="remember-me"。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<h3>表单登录</h3>
<form action="/authentication/form" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td colspan='2'>
<span style="display: none;">name remember-me 是固定的</span>
<input name="remember-me" type="checkbox" value="true" />
<span>记住我</span>
</td>
</tr>
<tr>
<td colspan="2"><button type="submit">登录</button></td>
</tr>
</table>
</form>
</body>
</html>
复制
config配置:
首先我们来配置一下TokenRepository。
@Autowired
private DataSource dataSource;
@Bean
public PersistentTokenRepository persistentTokenRepository() {
JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
tokenRepository.setDataSource(dataSource);
return tokenRepository;
}
复制
我们点击进入JdbcTokenRepositoryImpl 看一下:
这里面有一个CREATE_TABLE_SQL的变量,因为它要把token存入到数据库中所以要创建一个表,这个脚本可以拿到数据库中执行也可以设置参数:
@Bean
public PersistentTokenRepository persistentTokenRepository() {
JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
tokenRepository.setDataSource(dataSource);
//在启动的时候创建表 如果数据库有该表,再设置为true,启动会报错
tokenRepository.setCreateTableOnStartup(true);
return tokenRepository;
}
复制
然后我们SpringSecurity:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()//表单登录的方式
//自定义成功处理器
.successHandler(myAuthenticationSuccessHandler)
//自定义失败处理器
.failureHandler(myAuthenticationFailureHandler)
.and()
//以下是rememberMe的配置
.rememberMe()
.tokenRepository(persistentTokenRepository())//设置tokenRepository
.tokenValiditySeconds(3600)//token过期秒数,一般是一周或者两周
.userDetailsService(myUserDetailService)//指定userDetails用来登陆
.and()
.authorizeRequests()//要授权请求的意思
.antMatchers("/login.html").permitAll()//配置不拦截登陆页面
.anyRequest()//任何的请求
.authenticated()//都需要身份认证
.and()
.csrf().disable();//关掉跨站请求伪造的防护
}
复制
此时SpringSecurity的记住我功能已经实现了!
我们勾选记住我登录后查看数据库会出现一个表和数据:
然后我们重启系统后,再次请求会发现无需登录。
文章转载自魏卯卯,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。
评论
相关阅读
2025年4月中国数据库流行度排行榜:OB高分复登顶,崖山稳驭撼十强
墨天轮编辑部
1355次阅读
2025-04-09 15:33:27
2025年3月国产数据库大事记
墨天轮编辑部
741次阅读
2025-04-03 15:21:16
2025年3月国产数据库中标情况一览:TDSQL大单622万、GaussDB大单581万……
通讯员
538次阅读
2025-04-10 15:35:48
征文大赛 |「码」上数据库—— KWDB 2025 创作者计划启动
KaiwuDB
459次阅读
2025-04-01 20:42:12
数据库,没有关税却有壁垒
多明戈教你玩狼人杀
412次阅读
2025-04-11 09:38:42
优炫数据库成功应用于国家电投集团青海海南州新能源电厂!
优炫软件
385次阅读
2025-03-21 10:34:08
天津市政府数据库框采结果公布!
通讯员
317次阅读
2025-04-10 12:32:35
最近我为什么不写评论国产数据库的文章了
白鳝的洞穴
317次阅读
2025-04-07 09:44:54
国产数据库需要扩大场景覆盖面才能在竞争中更有优势
白鳝的洞穴
279次阅读
2025-04-14 09:40:20
从HaloDB体验到国产数据库兼容性
多明戈教你玩狼人杀
268次阅读
2025-04-07 09:36:17