Commit 7516440e by 刘宇峰

优化代码

1 parent b75a2a70
......@@ -67,10 +67,11 @@ public class GatewayService {
/**
* 签名的有效时间,默认24小时
*/
private Long jwtTtl = 24 * 60 * 60 * 1000L;
private Long jwtTtl = 24 * 60 * 60L;
/**
* 生效时间偏移量
*/
private Integer jwtIssueAtOffset;
}
......@@ -16,8 +16,10 @@ import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.time.Instant;
import java.util.*;
import java.util.Map.Entry;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
@Component
......@@ -67,40 +69,53 @@ public class GatewayJwtUtils {
public String createCachedToken(Map<String, Object> userMap, GatewayService gatewayService) {
String token = this.create(userMap, Instant.now(), gatewayService);
this.stringRedisTemplate.opsForValue().set(gatewayService.getName(), token, gatewayService.getJwtTtl(), TimeUnit.MILLISECONDS);
this.stringRedisTemplate.opsForValue().set(gatewayService.getName(), token, gatewayService.getJwtTtl(), TimeUnit.SECONDS);
log.debug("create id {} token [" + token + "]", gatewayService.getName());
return token;
}
private static String create(Map<String, Object> claims, Instant issueAt, GatewayService gatewayService) {
Algorithm algorithm = Algorithm.HMAC256(gatewayService.getSecret());
Instant iat = issueAt.plusSeconds(Objects.isNull(gatewayService.getJwtIssueAtOffset()) ? 0L : (long) (-gatewayService.getJwtIssueAtOffset()));
Instant exp = issueAt.plusSeconds(gatewayService.getJwtTtl());
Map<String, Object> newClaims = new HashMap();
Iterator var9 = claims.entrySet().iterator();
while (var9.hasNext()) {
Entry<String, Object> entry = (Entry) var9.next();
String key = (String) entry.getKey();
Object value = entry.getValue();
if (!"class".equals(key) && !Objects.isNull(value)) {
newClaims.put(key, value);
Map<String, Object> newClaims = new HashMap<>();
claims.forEach((k, v) -> {
if (!"class".equals(k) && !Objects.isNull(v)) {
newClaims.put(k, v);
}
}
JWTCreator.Builder builder = JWT.create().withJWTId(gatewayService.getName()).withClaim("iat", Date.from(issueAt.plusSeconds(gatewayService.getJwtIssueAtOffset() == null ? 0L : (long) (-gatewayService.getJwtIssueAtOffset())))).withClaim("exp", Date.from(exp)).withClaim("payloadMap", newClaims);
});
JWTCreator.Builder builder = JWT.create().withJWTId(gatewayService.getName())
.withClaim("iat", Date.from(iat))
.withClaim("exp", Date.from(exp))
.withClaim("payloadMap", newClaims);
builder.withSubject(gatewayService.getName()).withClaim("name", gatewayService.getName());
String token = builder.sign(algorithm);
log.trace("create token [" + token + "]; iat: " + Date.from(exp) + " exp: " + Date.from(exp));
log.trace("create token [" + token + "]; iat: " + Date.from(iat) + " exp: " + Date.from(exp));
return token;
}
public DecodedJWT decode(String token) {
if (StringUtils.isEmpty(token)) {
return null;
}
if (token.startsWith(BEARER)) {
token = token.replace(BEARER, "");
}
return com.auth0.jwt.JWT.decode(token);
DecodedJWT decodedJWT = null;
try {
decodedJWT = JWT.decode(token);
} catch (Exception e) {
log.error("decode token failed , {}", e.toString());
}
return decodedJWT;
}
public DecodedJWT verify(String token, GatewayService gatewayService) {
if (StringUtils.isEmpty(token)) {
return null;
}
if (Objects.isNull(gatewayService)) {
return null;
}
......@@ -197,17 +212,19 @@ public class GatewayJwtUtils {
Instant exp = jwtToken.getExpiresAt().toInstant();
Algorithm algorithm = Algorithm.HMAC256(gatewayService.getSecret());
Instant newExp = exp.plusSeconds(gatewayService.getJwtTtl());
String token = JWT.create().withJWTId(jwtToken.getId()).withClaim("sub", jwtToken.getSubject()).withClaim("iat", Date.from(exp)).withClaim("exp", Date.from(newExp)).withClaim("payloadMap", jwtToken.getClaim("payloadMap").asMap()).sign(algorithm);
String token = JWT.create().withJWTId(jwtToken.getId())
.withClaim("sub", jwtToken.getSubject())
.withClaim("iat", Date.from(now))
.withClaim("exp", Date.from(newExp))
.withClaim("payloadMap", jwtToken.getClaim("payloadMap").asMap())
.sign(algorithm);
log.debug("create refresh token [" + token + "]; iat: " + Date.from(exp) + " exp: " + Date.from(newExp));
return token;
}
public void destroyToken(String token) {
this.decode(token);
}
public void destroyCachedToken(String token) {
DecodedJWT decodedJWT = this.decode(token);
this.stringRedisTemplate.delete(decodedJWT.getId());
}
}
......@@ -4,12 +4,12 @@ import cn.com.glsx.auth.config.ApiGatewayServiceConfig;
import cn.com.glsx.auth.model.GatewayService;
import cn.com.glsx.auth.model.OpenApiResult;
import cn.com.glsx.auth.modules.request.QueryAccessTokenRequest;
import cn.com.glsx.auth.modules.utils.SM3Utils;
import cn.com.glsx.auth.utils.GatewayJwtUtils;
import com.glsx.plat.common.annotation.SysLog;
import com.glsx.plat.common.enums.OperateType;
import com.glsx.plat.common.utils.DateUtils;
import com.glsx.plat.common.utils.MD5Util;
import com.glsx.plat.common.utils.SM3Utils;
import com.glsx.plat.exception.OpenApiResultException;
import com.glsx.plat.exception.ResultException;
import io.swagger.v3.oas.annotations.Operation;
......
package cn.com.glsx.auth.modules.utils;
import com.glsx.plat.common.utils.MD5Util;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.Arrays;
public class SM3Utils {
private static final String ENCODING = "UTF-8";
static {
Security.addProvider(new BouncyCastleProvider());
}
/**
* sm3 算法加密
*
* @param paramStr 待加密的参数字符串
* @param appKey 加密的密钥 appKey(接口访问秘钥 Key)
* @return 返回 SM3 加密后固定长度为 32 的 16 进制密内容文字符串
* @explain
*/
public static String encrypt(String paramStr, String appKey) {
// 将返回的 hash 值转换成 16 进制字符串
String resultHexStr = "";
try {
// 将字符串转换成 byte 数组
byte[] srcData = paramStr.getBytes(ENCODING);
// 调用 hash()
byte[] resultHash = hmac(srcData, appKey.getBytes(ENCODING));
// 将返回的 hash 值转换成 16 进制字符串
resultHexStr = ByteUtils.toHexString(resultHash);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return resultHexStr;
}
/**
* 通过密钥进行哈希
*
* @param appKey 加密的密钥 appKey 的 byte 数组
* @param srcData 被加密参数字符串的 byte 数组
* @return
*/
public static byte[] hmac(byte[] appKey, byte[] srcData) {
KeyParameter keyParameter = new KeyParameter(appKey);
SM3Digest digest = new SM3Digest();
HMac mac = new HMac(digest);
mac.init(keyParameter);
mac.update(srcData, 0, srcData.length);
byte[] result = new byte[mac.getMacSize()];
mac.doFinal(result, 0);
return result;
}
/**
* 第 8 页 共 105 页
* 第 9 页 共 105 页
* 判断待加密的原始数据与加密后的数据是否一致
*
* @param paramStr 待加密的参数字符串
* @param resultHexStr SM3 加密后固定长度为 32 的 16 进制密内容文字符串
* @param appKey 加密的密钥 appKey 的 byte 数组
* @return 校验结果
*/
public static boolean verify(String paramStr, String resultHexStr, String appKey) {
boolean flag = false;
try {
byte[] srcData = paramStr.getBytes(ENCODING);
byte[] sm3Hash = ByteUtils.fromHexString(resultHexStr);
byte[] newHash = hmac(srcData, appKey.getBytes(ENCODING));
if (Arrays.equals(newHash, sm3Hash)) {
flag = true;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return flag;
}
public static void main(String[] args) {
// // 待加密的待加密的参数字符串
// String paramStr = "6bba9d97c252661067758b2b6f80e7c558e562b8";
// // 加密的密钥 appKey
// String appKey = "RaOF35Kw";
// // sm3 算法加密
// String resultHexStr = SM3Utils.encrypt(paramStr, appKey);
// System.out.println("待加密的待加密的参数字符串:" + paramStr);
// System.out.println("SM3 加密后的密文字符串内容:" + resultHexStr);
// System.out.println("校验结果:" + SM3Utils.verify(paramStr, resultHexStr, appKey));
System.out.println(System.currentTimeMillis());
System.out.println(MD5Util.convert32("e7794d5173c29275ed74f3e8fc2d9d8171d3d7d3a8953f27").toLowerCase());
}
}
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!