spring-security的记住我功能和显示当前用户名

方式一

  1. 导入spring相关的依赖
  2. 登录页面中的记住我的代码里的name值一定要是remember-me,value值可以是true、on、1都可以
<div class="form-group">
			<label for="remember-me">是否记住</label>
			<input type="checkbox" name="remember-me" value="true"/> Remember me
		</div>
  1. 开启remberme 的过滤器,设置token的存在时间(单位:秒),在<security:http />标签中加
<security:remember-me token-validity-seconds="60"/>

方式二(持久化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,
	primary key(series)
)ENGINE=InnoDB DEFAULT CHARSET=utf8

2.这里的数据源是spring的配置文件里所配置了的

<security:remember-me 
	data-source-ref="dataSource"
	token-validity-seconds="60"/>

显示当前用户名
若是后端想要知道当前通过认证的用户名,可以利用以下代码实现

 //从后台获取当前获取到的通过认证的用户
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        System.out.println(name);

若是前台页面想要展示当前的用户名,则可以在前端页面上加入以下代码
首先是加入头标签

<%@taglib uri="http://www.springframework.org/security/tags" prefix="security"%>

然后在想要显示用户名的区域加入以下代码:

<security:authentication property="principal.username"/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值