mirror of
https://codeup.aliyun.com/67762337eccfc218f6110e0e/per-boe/java-servers.git
synced 2025-12-17 23:06:53 +08:00
64 lines
2.0 KiB
Java
64 lines
2.0 KiB
Java
package com.xboe.config;
|
|
import com.alibaba.fastjson.JSON;
|
|
import com.alibaba.fastjson.JSONObject;
|
|
import com.alibaba.fastjson.TypeReference;
|
|
import com.xboe.common.utils.Sha256Mac;
|
|
import org.apache.commons.codec.binary.Base64;
|
|
|
|
import java.util.Map;
|
|
|
|
/**
|
|
* Jwt工具类
|
|
*
|
|
* @author ruoyi
|
|
*/
|
|
public class JwtUtils {
|
|
|
|
public static final String secretKey = "JDF_BOE";
|
|
|
|
/**
|
|
* 从数据声明生成令牌
|
|
*
|
|
* @param claims 数据声明
|
|
* @return 令牌
|
|
*/
|
|
public static String createToken(Map<String, Object> claims) {
|
|
JSONObject header = new JSONObject();
|
|
header.put("alg", "HS256");
|
|
header.put("type", "token");
|
|
String payload64 = Base64.encodeBase64String(JSON.toJSONString(claims).getBytes());
|
|
String header64 = Base64.encodeBase64String(header.toString().getBytes());
|
|
String sign = Sha256Mac.sha256_mac(header64 + payload64, secretKey);
|
|
return header64 + "." + payload64 + "." + sign;
|
|
}
|
|
|
|
/**
|
|
* 从令牌中获取数据声明
|
|
*
|
|
* @param token 令牌
|
|
* @return 数据声明
|
|
*/
|
|
public static Map<String, Object> parseToken(String token) throws ConditionException {
|
|
String[] tokens = token.split("\\.");
|
|
if (tokens.length != 3) {
|
|
throw new ConditionException("token不合法 : " + token);
|
|
}
|
|
String payload = new String(Base64.decodeBase64(tokens[1]));
|
|
String sign = Sha256Mac.sha256_mac(tokens[0] + tokens[1], secretKey);
|
|
if (sign.equals(tokens[2])) {
|
|
JSONObject jsonObject = JSON.parseObject(payload);
|
|
long exp = jsonObject.getLong("exp");
|
|
long now = System.currentTimeMillis() / 1000;
|
|
if (now > exp) {
|
|
throw new ConditionException("token过期 : " + token);
|
|
}
|
|
Map<String, Object> map = JSON.parseObject(payload, new TypeReference<Map<String, Object>>() {
|
|
});
|
|
return map;
|
|
} else {
|
|
throw new ConditionException("token错误 : " + token);
|
|
}
|
|
}
|
|
|
|
}
|