通常系统都会限制同一个账号的登录人数,多人登录要么限制后者登录,要么踢出前者,Spring Security 提供了这样的功能,本文讲解一下在没有使用Security的时候如何手动实现这个功能
本文借鉴了:
https://jinnianshilongnian.iteye.com/blog/2039760, 如果你是使用 Shiro + Session 的模式,推荐阅读此文
Demo 技术选型
-
SpringBoot
-
JWT
-
Filter
-
Redis + Redisson
JWT(token)存储在Redis中,类似 JSessionId-Session的关系,用户登录后每次请求在Header中携带jwt
如果你是使用session的话,也完全可以借鉴本文的思路,只是代码上需要加些改动
两种实现思路
比较时间戳
维护一个 username: jwtToken
这样的一个 key-value
在Reids中, Filter逻辑如下:
public class CompareKickOutFilter extends KickOutFilter {
@Autowired
private UserService userService;
@Override
public boolean isAccessAllowed(HttpServletRequest request, HttpServletResponse response) {
String token = request.getHeader("Authorization");
String username = JWTUtil.getUsername(token);
String userKey = PREFIX + username;
RBucket<String> bucket = redissonClient.getBucket(userKey);
String redisToken = bucket.get();
if (token.equals(redisToken)) {
return true;
} else if (StringUtils.isBlank(redisToken)) {
bucket.set(token);
} else {
Long redisTokenUnixTime = JWTUtil.getClaim(redisToken, "createTime").asLong();
Long tokenUnixTime = JWTUtil.getClaim(token, "createTime").asLong();
if (tokenUnixTime.compareTo(redisTokenUnixTime) > 0) {
bucket.set(token);
} else {
userService.logout(token);
sendJsonResponse(response, 4001, "您的账号已在其他设备登录");
return false;
}
}
return true;
}
}
队列踢出
public class QueueKickOutFilter extends KickOutFilter {
private boolean kickoutAfter = false;
private int maxSession = 1;
public void setKickoutAfter(boolean kickoutAfter) {
this.kickoutAfter = kickoutAfter;
}
public void setMaxSession(int maxSession) {
this.maxSession = maxSession;
}
@Override
public boolean isAccessAllowed(HttpServletRequest request, HttpServletResponse response) throws Exception {
String token = request.getHeader("Authorization");
UserBO currentSession = CurrentUser.get();
Assert.notNull(currentSession, "currentSession cannot null");
String username = currentSession.getUsername();
String userKey = PREFIX + "deque_" + username;
String lockKey = PREFIX_LOCK + username;
RLock lock = redissonClient.getLock(lockKey);
lock.lock(2, TimeUnit.SECONDS);
try {
RDeque<String> deque = redissonClient.getDeque(userKey);
if (!deque.contains(token) && currentSession.isKickout() == false) {
deque.push(token);
}
while (deque.size() > maxSession) {
String kickoutSessionId;
if (kickoutAfter) {
kickoutSessionId = deque.removeFirst();
} else {
kickoutSessionId = deque.removeLast();
}
try {
RBucket<UserBO> bucket = redissonClient.getBucket(kickoutSessionId);
UserBO kickoutSession = bucket.get();
if (kickoutSession != null) {
kickoutSession.setKickout(true);
bucket.set(kickoutSession);
}
} catch (Exception e) {
}
}
if (currentSession.isKickout()) {
try {
userService.logout(token);
sendJsonResponse(response, 4001, "您的账号已在其他设备登录");
} catch (Exception e) {
}
return false;
}
} finally {
if (lock.isHeldByCurrentThread()) {
lock.unlock();
LOGGER.info(Thread.currentThread().getName() + " unlock");
} else {
LOGGER.info(Thread.currentThread().getName() + " already automatically release lock");
}
}
return true;
}
}
1. 第一种方法逻辑简单粗暴, 只维护一个key-value 不需要使用锁,非要说缺点的话没有第二种方法灵活。
2. 第二种方法我很喜欢,代码很优雅灵活,但是逻辑相对麻烦一些,而且为了保证线程安全地操作队列,要使用分布式锁。目前我们项目中使用的是第一种方法
演示
下载地址:
gitee.com/yintianwen7/taven-springboot-learning/tree/master/login-control
1. 运行项目,访问localhost:8887 demo中没有存储用户信息,随意输入用户名密码,用户名相同则被踢出
2. 访问 localhost:8887/index.html 弹出用户信息, 代表当前用户有效
3. 另一个浏览器登录相同用户名,回到第一个浏览器刷新页面,提示被踢出
4. application.properties中选择开启哪种过滤器模式,默认是比较时间戳踢出,开启队列踢出queue-filter.enabled=true。
*:该文章是转载(为了学习打卡),如果需要删除请联系我,。