优化检测用户token机制,不查询全库数据

This commit is contained in:
朱耘稷
2021-03-04 16:00:56 +08:00
parent ffc43ce97b
commit ebffa204f2
4 changed files with 39 additions and 44 deletions

View File

@ -67,16 +67,16 @@ public class PermissionInterceptor extends HandlerInterceptorAdapter {
} }
String token = tokens[1]; String token = tokens[1];
//检测用户是否被踢出
if(redisUtils.get(ShopConstants.YSHOP_APP_LOGIN_USER + token) == null){
throw new UnAuthenticatedException(ApiCode.UNAUTHORIZED);
}
Optional<Map<String, Claim>> optionalMap = JwtToken.getClaims(token); Optional<Map<String, Claim>> optionalMap = JwtToken.getClaims(token);
Map<String, Claim> map = optionalMap Map<String, Claim> map = optionalMap
.orElseThrow(() -> new UnAuthenticatedException(ApiCode.UNAUTHORIZED)); .orElseThrow(() -> new UnAuthenticatedException(ApiCode.UNAUTHORIZED));
String uName = map.get("uName").asString();
//检测用户是否被踢出
if (redisUtils.get(ShopConstants.YSHOP_APP_LOGIN_USER + uName + ":" + token) == null) {
throw new UnAuthenticatedException(ApiCode.UNAUTHORIZED);
}
boolean valid = this.hasPermission(authCheck.get(), map); boolean valid = this.hasPermission(authCheck.get(), map);
if(valid){ if(valid){
this.setToThreadLocal(map); this.setToThreadLocal(map);

View File

@ -74,21 +74,22 @@ public class JwtToken {
} }
public static String makeToken(Long uid, Integer scope) { public static String makeToken(Long uid,String uName, Integer scope) {
return JwtToken.getToken(uid, scope); return JwtToken.getToken(uid,uName, scope);
} }
public static String makeToken(Long uid) { public static String makeToken(Long uid,String uName) {
return JwtToken.getToken(uid, JwtToken.defaultScope); return JwtToken.getToken(uid,uName, JwtToken.defaultScope);
} }
private static String getToken(Long uid, Integer scope) { private static String getToken(Long uid,String uName, Integer scope) {
Algorithm algorithm = Algorithm.HMAC256(JwtToken.jwtKey); Algorithm algorithm = Algorithm.HMAC256(JwtToken.jwtKey);
Map<String,Date> map = JwtToken.calculateExpiredIssues(); Map<String,Date> map = JwtToken.calculateExpiredIssues();
return JWT.create() return JWT.create()
.withClaim("uid", uid) .withClaim("uid", uid)
.withClaim("scope", scope) .withClaim("scope", scope)
.withClaim("uName", uName)
.withExpiresAt(map.get("expiredTime")) .withExpiresAt(map.get("expiredTime"))
.withIssuedAt(map.get("now")) .withIssuedAt(map.get("now"))
.sign(algorithm); .sign(algorithm);

View File

@ -14,6 +14,7 @@ import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil; import cn.hutool.crypto.SecureUtil;
import co.yixiang.api.ApiResult; import co.yixiang.api.ApiResult;
import co.yixiang.api.YshopException; import co.yixiang.api.YshopException;
import co.yixiang.common.bean.LocalUser;
import co.yixiang.common.enums.SmsTypeEnum; import co.yixiang.common.enums.SmsTypeEnum;
import co.yixiang.common.util.JwtToken; import co.yixiang.common.util.JwtToken;
import co.yixiang.common.util.SmsUtils; import co.yixiang.common.util.SmsUtils;
@ -79,7 +80,7 @@ public class AuthController {
HttpServletRequest request) { HttpServletRequest request) {
YxUser yxUser = authService.wxappLogin(loginParam); YxUser yxUser = authService.wxappLogin(loginParam);
String token = JwtToken.makeToken(yxUser.getUid()); String token = JwtToken.makeToken(yxUser.getUid(),yxUser.getUsername());
String expiresTimeStr = JwtToken.getExpireTime(token); String expiresTimeStr = JwtToken.getExpireTime(token);
// 返回 token // 返回 token
@ -113,7 +114,7 @@ public class AuthController {
HttpServletRequest request) { HttpServletRequest request) {
YxUser yxUser = authService.wechatLogin(code,spread); YxUser yxUser = authService.wechatLogin(code,spread);
String token = JwtToken.makeToken(yxUser.getUid()); String token = JwtToken.makeToken(yxUser.getUid(),yxUser.getUsername());
String expiresTimeStr = JwtToken.getExpireTime(token); String expiresTimeStr = JwtToken.getExpireTime(token);
@ -147,7 +148,7 @@ public class AuthController {
throw new YshopException("账号或者密码不正确"); throw new YshopException("账号或者密码不正确");
} }
String token = JwtToken.makeToken(yxUser.getUid()); String token = JwtToken.makeToken(yxUser.getUid(),yxUser.getUsername());
String expiresTimeStr = JwtToken.getExpireTime(token); String expiresTimeStr = JwtToken.getExpireTime(token);
// 保存在线信息 // 保存在线信息
@ -237,7 +238,7 @@ public class AuthController {
String bearerToken = request.getHeader("Authorization"); String bearerToken = request.getHeader("Authorization");
String[] tokens = bearerToken.split(" "); String[] tokens = bearerToken.split(" ");
String token = tokens[1]; String token = tokens[1];
authService.logout(token); authService.logout(LocalUser.getUser().getUsername(), token);
return ApiResult.ok("退出成功"); return ApiResult.ok("退出成功");
} }

View File

@ -300,74 +300,67 @@ public class AuthService {
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
redisUtils.set(ShopConstants.YSHOP_APP_LOGIN_USER + token, onlineUser, AuthService.expiredTimeIn); redisUtils.set(ShopConstants.YSHOP_APP_LOGIN_USER +onlineUser.getUserName() + ":" + token, onlineUser, AuthService.expiredTimeIn);
} }
/** /**
* 检测用户是否在之前已经登录,已经登录踢下线 * 检测用户是否在之前已经登录,已经登录踢下线
*
* @param userName 用户名 * @param userName 用户名
*/ */
public void checkLoginOnUser(String userName, String igoreToken){ public void checkLoginOnUser(String userName, String igoreToken) {
List<OnlineUser> onlineUsers = this.getAll(userName); List<OnlineUser> onlineUsers = this.getAll(userName);
if(onlineUsers ==null || onlineUsers.isEmpty()){ if (onlineUsers == null || onlineUsers.isEmpty()) {
return; return;
} }
System.out.println("onlineUsers:"+onlineUsers); for (OnlineUser onlineUser : onlineUsers) {
for(OnlineUser onlineUser:onlineUsers){ try {
if(onlineUser.getUserName().equals(userName)){ String token = EncryptUtils.desDecrypt(onlineUser.getKey());
try { if (StringUtils.isNotBlank(igoreToken) && !igoreToken.equals(token)) {
String token = EncryptUtils.desDecrypt(onlineUser.getKey()); this.kickOut(userName, onlineUser.getKey());
if(StringUtils.isNotBlank(igoreToken)&&!igoreToken.equals(token)){ } else if (StringUtils.isBlank(igoreToken)) {
this.kickOut(onlineUser.getKey()); this.kickOut(userName, onlineUser.getKey());
}else if(StringUtils.isBlank(igoreToken)){
this.kickOut(onlineUser.getKey());
}
} catch (Exception e) {
log.error("checkUser is error",e);
} }
} catch (Exception e) {
log.error("checkUser is error", e);
} }
} }
} }
/** /**
* 踢出用户 * 踢出用户
*
* @param key / * @param key /
*/ */
public void kickOut(String key) throws Exception { public void kickOut(String userName, String key) throws Exception {
key = ShopConstants.YSHOP_APP_LOGIN_USER + EncryptUtils.desDecrypt(key); key = ShopConstants.YSHOP_APP_LOGIN_USER + userName + ":" + EncryptUtils.desDecrypt(key);
redisUtils.del(key); redisUtils.del(key);
} }
/** /**
* 退出登录 * 退出登录
* @param token / * @param token /
*/ */
public void logout(String token) { public void logout(String userName,String token) {
String key = ShopConstants.YSHOP_APP_LOGIN_USER + token; String key = ShopConstants.YSHOP_APP_LOGIN_USER+ userName + ":" + token;
redisUtils.del(key); redisUtils.del(key);
} }
/** /**
* 查询全部数据,不分页 * 查询全部数据,不分页
* @param filter / *
* @param uName /
* @return / * @return /
*/ */
private List<OnlineUser> getAll(String filter){ private List<OnlineUser> getAll(String uName) {
List<String> keys = null; List<String> keys = null;
keys = redisUtils.scan(ShopConstants.YSHOP_APP_LOGIN_USER + "*"); keys = redisUtils.scan(ShopConstants.YSHOP_APP_LOGIN_USER + uName + ":" + "*");
Collections.reverse(keys); Collections.reverse(keys);
List<OnlineUser> onlineUsers = new ArrayList<>(); List<OnlineUser> onlineUsers = new ArrayList<>();
for (String key : keys) { for (String key : keys) {
OnlineUser onlineUser = (OnlineUser) redisUtils.get(key); OnlineUser onlineUser = (OnlineUser) redisUtils.get(key);
if(StringUtils.isNotBlank(filter)){ onlineUsers.add(onlineUser);
if(onlineUser.toString().contains(filter)){
onlineUsers.add(onlineUser);
}
} else {
onlineUsers.add(onlineUser);
}
} }
onlineUsers.sort((o1, o2) -> o2.getLoginTime().compareTo(o1.getLoginTime())); onlineUsers.sort((o1, o2) -> o2.getLoginTime().compareTo(o1.getLoginTime()));
return onlineUsers; return onlineUsers;