Files
yexuejc-base/src/main/java/com/yexuejc/base/util/JwtUtil.java
2024-09-01 16:47:43 +08:00

163 lines
4.6 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.yexuejc.base.util;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;
import javax.crypto.SecretKey;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SecureDigestAlgorithm;
/**
* jwt工具类
* <p>
* 升级2.0
* <br/>
* 由静态类分装成单例类可配置参数config()
* </p>
*
* @author maxf
* @version 2.0
* @ClassName JwtUtil
* @Description
* @date 2018/9/3 15:28
*/
public class JwtUtil {
private JwtUtil() {
}
public static JwtUtil instace() {
return Instace.jwtUtil;
}
/**
* 参数配置:设置一次即可,多次设置会覆盖之前的
*
* @param type 加密类型默认JWT
* @param iss token发行商: 默认yexuejc.top
* @param key 加密key 默认h%OG8Y3WgA5AN7&6Ke7I#C1XvneW0N8a
* @param algorithm 加密方式
* @return
*/
public static JwtUtil config(String type, String iss, String key, SecureDigestAlgorithm<SecretKey, SecretKey> algorithm) {
JwtUtil jwtUtil = instace();
if (null != key) {
jwtUtil.jwtSignatureKey = key;
}
if (null != type) {
jwtUtil.jwtHeaderTyp = type;
}
if (null != iss) {
jwtUtil.jwtClaimsIss = iss;
}
if (null != algorithm) {
jwtUtil.algorithm = algorithm;
}
return jwtUtil;
}
private static class Instace {
private static JwtUtil jwtUtil = new JwtUtil();
}
/**
* 加密用KEY
*/
private String jwtSignatureKey = "h%OG8Y3WgA5AN7&6Ke7I#C1XvneW0N8a";
/**
* token类型
*/
private String jwtHeaderTyp = "JWT";
/**
* token发行商
*/
private String jwtClaimsIss = "yexuejc.top";
private SecureDigestAlgorithm<SecretKey, SecretKey> algorithm = Jwts.SIG.HS512;
/**
* 加密内容生成token
*
* @param subjectObj
* @return
*/
public String compact(Object subjectObj) {
return compact(null, subjectObj);
}
public String compact(String subId, Object subjectObj) {
String subject = subId;
Map<String, Object> subMap = JsonUtil.objToMap(subjectObj, String.class, Object.class);
if (StrUtil.isEmpty(subject)) {
if (subjectObj instanceof String) {
subject = (String) subjectObj;
} else if (StrUtil.isNotEmpty(subMap)) {
Object sid = subMap.get("subId");
Object s = subMap.get("sub");
subject = StrUtil.isNotEmpty(sid) ? String.valueOf(sid) : String.valueOf(s);
}
}
Date now = new Date();
return Jwts.builder()
// 设置token的唯一标识IDclaims.jti
.id(StrUtil.genUUID())
// 设置token类型header.typ
.header().add("typ", jwtHeaderTyp).and()
// 设置token发行时间为当前时间claims.iat
.issuedAt(now).claims(JsonUtil.objToMap(subjectObj, String.class, Object.class))
// 设置token发行商/发行者claims.iss
.issuer(jwtClaimsIss)
// 设置token用户定义主体claims.sub
.subject(subject)
// 设置算法签名,(密钥,加密算法)
.signWith(getSecretKey(), algorithm)
// 生成token
.compact();
}
/**
* 解密token为一个Map
*
* @param token
* @return
*/
public Map<?, ?> parse(String token) {
return parse(token, Map.class);
}
/**
* 解密token为一个指定对象
*
* @param token
* @param cls
* @return
*/
public <T> T parse(String token, Class<T> cls) {
return JsonUtil.json2Obj(JsonUtil.obj2Json(parseStr(token)), cls);
}
/**
* 解密token为字符串
*
* @param token
* @return
*/
public Claims parseStr(String token) {
return Jwts.parser().verifyWith(getSecretKey()).build().parseSignedClaims(token).getPayload();
}
private SecretKey getSecretKey() {
int minLen = 32;
if (jwtSignatureKey.length() % minLen != 0) {
// 补齐32的倍数,左补0
String format = "%" + ((jwtSignatureKey.length() / minLen + 1) * minLen) + "s";
jwtSignatureKey = String.format(format, jwtSignatureKey).replace(' ', '0');
}
byte[] bytes = jwtSignatureKey.getBytes(StandardCharsets.UTF_8);
return Keys.hmacShaKeyFor(bytes);
}
}