|
|
|
@ -0,0 +1,67 @@
|
|
|
|
|
package com.dsideal.gw.Util;
|
|
|
|
|
|
|
|
|
|
import com.dsideal.gw.GwApplication;
|
|
|
|
|
import com.dsideal.gw.Plugin.YamlProp;
|
|
|
|
|
import io.jsonwebtoken.Claims;
|
|
|
|
|
import io.jsonwebtoken.Jwts;
|
|
|
|
|
import io.jsonwebtoken.SignatureAlgorithm;
|
|
|
|
|
|
|
|
|
|
import java.nio.charset.StandardCharsets;
|
|
|
|
|
import java.util.HashMap;
|
|
|
|
|
import java.util.Map;
|
|
|
|
|
import java.util.Date;
|
|
|
|
|
|
|
|
|
|
public class JwtUtil {
|
|
|
|
|
public static final String AUTHORIZATION_STARTER = "Bearer ";
|
|
|
|
|
public static final String SECRET = GwApplication.PropKit.get("SECRET");
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 功能:黄海开发的生成JWT函数
|
|
|
|
|
*
|
|
|
|
|
* @param identity_id 身份ID
|
|
|
|
|
* @param person_id 人员ID
|
|
|
|
|
* @return JWT签名
|
|
|
|
|
*/
|
|
|
|
|
public static String generateToken(int identity_id, String person_id) {
|
|
|
|
|
// 获取当前日期和时间
|
|
|
|
|
Date now = new Date();
|
|
|
|
|
// 格式化日期
|
|
|
|
|
Map<String, Object> claims = new HashMap<>();
|
|
|
|
|
claims.put("create_time", now.toString());
|
|
|
|
|
claims.put("identity_id", identity_id);
|
|
|
|
|
claims.put("person_id", person_id);
|
|
|
|
|
return AUTHORIZATION_STARTER + Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS256, SECRET).compact();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static Claims getClaims(String token) {
|
|
|
|
|
if (token.contains(AUTHORIZATION_STARTER)) {
|
|
|
|
|
token = token.replace(AUTHORIZATION_STARTER, "");
|
|
|
|
|
}
|
|
|
|
|
Claims claims;
|
|
|
|
|
try {
|
|
|
|
|
claims = Jwts.parser()
|
|
|
|
|
.setSigningKey(SECRET)
|
|
|
|
|
.parseClaimsJws(token)
|
|
|
|
|
.getBody();
|
|
|
|
|
} catch (Exception e) {
|
|
|
|
|
try {
|
|
|
|
|
claims = Jwts.parser()
|
|
|
|
|
.setSigningKey(SECRET.getBytes(StandardCharsets.UTF_8))
|
|
|
|
|
.parseClaimsJws(token)
|
|
|
|
|
.getBody();
|
|
|
|
|
} catch (Exception err) {
|
|
|
|
|
claims = null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return claims;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static void main(String[] args) {
|
|
|
|
|
GwApplication gw = new GwApplication();
|
|
|
|
|
String token = generateToken(4, "0b64e31e-a85e-43eb-ba5f-3088d986a8da");
|
|
|
|
|
|
|
|
|
|
Claims claims = getClaims(token);
|
|
|
|
|
System.out.println(claims.get("identity_id"));
|
|
|
|
|
System.out.println(claims.get("person_id"));
|
|
|
|
|
}
|
|
|
|
|
}
|