通常系统都会限制同一个账号的登录人数,多人登录要么限制后者登录,要么踢出前者,Spring Security 提供了这样的功能,本文讲解一下在没有使用Security的时候如何手动实现这个功能
demo 技术选型
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(); // token > redisToken 则覆盖 if (tokenUnixTime.compareTo(redisTokenUnixTime) > 0) { bucket.set(token); } else { // 注销当前token userService.logout(token); sendJsonResponse(response, 4001, "您的账号已在其他设备登录"); return false; } } return true; } }
队列踢出
public class QueueKickOutFilter extends KickOutFilter { /** * 踢出之前登录的/之后登录的用户 默认踢出之前登录的用户 */ private boolean kickoutAfter = false; /** * 同一个帐号最大会话数 默认1 */ 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); // 如果队列里没有此token,且用户没有被踢出;放入队列 if (!deque.contains(token) && currentSession.isKickout() == false) { deque.push(token); } // 如果队列里的sessionId数超出最大会话数,开始踢人 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) { // 设置会话的kickout属性表示踢出了 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; } }
比较两种方法
演示
下载地址: https://gitee.com/yintianwen7/taven-springboot-learning/tree/master/login-control
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。