JAVA全系列 教程
3762个小节阅读:7090.3k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
在后台管理中,我们常常需要查看在线的用户,然后管理用户,有时候还需要踢出恶意操作的用户。在Spring Security中提供了Session注册器SessionRegistry,利用Session注册器可以强制用户下线。
在容器中注入SessionRegistry
xxxxxxxxxx
// 注入SessionRegistry
@Bean
public SessionRegistry sessionRegistry(){
return new SessionRegistryImpl();
}
编写踢出用户的方法
xxxxxxxxxx
@Autowired
private SessionRegistry sessionRegistry;
// 踢出指定用户
@GetMapping("/kickOut")
public void kickOutUser(String username) {
// 1.获取全部登录用户
List<Object> allPrincipals = sessionRegistry.getAllPrincipals();
// 2.遍历全部登录用户,找到要强制登出的用户
for (Object principal : allPrincipals) {
UserDetails userDetail = (UserDetails) principal;
if (username.equals(userDetail.getUsername())) {
// 3.找到认证用户所有的会话,不包含过期会话
List<SessionInformation> sessions = sessionRegistry.getAllSessions(userDetail, false);
if (null != sessions && !sessions.isEmpty()) {
// 4.遍历该用户的会话,使其立即失效
for (SessionInformation session : sessions) {
session.expireNow();
}
}
}
}
}