jwt token中获取loginType通过loginType获取StpLogic

This commit is contained in:
binarypursuer 2025-04-03 00:03:11 +08:00
parent 8cff63b0fc
commit 897b1d9215

View File

@ -0,0 +1,87 @@
package cn.dev33.satoken.jwt;
import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.jwt.error.SaJwtErrorCode;
import cn.dev33.satoken.jwt.exception.SaJwtException;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTException;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* JWT版本SaToken管理器
*
* @author binarypursuer
* @version 1.0
* @date 2025/4/2
*/
public class JwtSaManager {
/**
* StpLogic 集合, 记录框架所有成功初始化的 StpLogic
*/
public static Map<String, StpLogic> stpLogicMap = new LinkedHashMap<>();
/**
* 登录类型
*/
private static final String LOGIN_TYPE = "loginType";
/**
* 向全局集合中 put 一个 StpLogic
*
* @param stpLogic StpLogic
* @author binarypursuer
* @date 2025/4/2
* @since 1.0
**/
public static void putStpLogic(StpLogic stpLogic) {
stpLogicMap.put(stpLogic.getLoginType(), stpLogic);
}
/**
* 获取 StpLogic
*
* @param tokenName Token名称
* @return cn.dev33.satoken.stp.StpLogic
* @author binarypursuer
* @date 2025/4/2
* @since 1.0
**/
public StpLogic getStpLogic(String tokenName) {
// 获取当前请求的token
String token = SaHolder.getRequest().getHeader(tokenName);
// 判断token是否为空
if (token == null) {
return null;
}
// 解析Token
JWT jwt;
try {
jwt = JWT.of(token);
} catch (JWTException | JSONException e) {
throw new SaJwtException("jwt 解析失败:" + token, e).setCode(SaJwtErrorCode.CODE_30201);
}
JSONObject payloads = jwt.getPayloads();
//获取登录类型
String loginType = payloads.getStr(LOGIN_TYPE);
// 获取 StpLogic
return stpLogicMap.get(loginType);
}
/**
* 获取 StpLogic
*
* @return cn.dev33.satoken.stp.StpLogic
* @author binarypursuer
* @date 2025/4/2
* @since 1.0
**/
public StpLogic getStpLogic() {
return getStpLogic(StpUtil.getTokenName());
}
}