From 7cde8dafae3c2bb77e9c723d2919a6fa1ee6b258 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E5=82=85=E5=93=A5?= <184172133@qq.com> Date: Tue, 10 Oct 2023 22:04:09 +0800 Subject: [PATCH] =?UTF-8?q?feat=EF=BC=9A=E6=99=BA=E8=B0=B1Ai=E7=AD=BE?= =?UTF-8?q?=E5=90=8DToken=E5=B7=A5=E5=85=B7=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chatglm/utils/BearerTokenUtils.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/main/java/cn/bugstack/chatglm/utils/BearerTokenUtils.java diff --git a/src/main/java/cn/bugstack/chatglm/utils/BearerTokenUtils.java b/src/main/java/cn/bugstack/chatglm/utils/BearerTokenUtils.java new file mode 100644 index 0000000..57954fc --- /dev/null +++ b/src/main/java/cn/bugstack/chatglm/utils/BearerTokenUtils.java @@ -0,0 +1,57 @@ +package cn.bugstack.chatglm.utils; + +import com.auth0.jwt.JWT; +import com.auth0.jwt.algorithms.Algorithm; +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import lombok.extern.slf4j.Slf4j; + +import java.nio.charset.StandardCharsets; +import java.util.Calendar; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +/** + * @author 小傅哥,微信:fustack + * @description 签名工具包;过期时间30分钟,缓存时间29分钟 + * @github https://github.com/fuzhengwei + * @Copyright 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! + */ +@Slf4j +public class BearerTokenUtils { + + // 过期时间;默认30分钟 + private static final int expireMillis = 30 * 60 * 1000; + + // 缓存服务 + public static Cache cache = CacheBuilder.newBuilder() + .expireAfterWrite(expireMillis - (60 * 1000), TimeUnit.MINUTES) + .build(); + + /** + * 对 ApiKey 进行签名 + * + * @param apiKey 登录创建 ApiKey apikeys + * @param apiSecret apiKey的后半部分 828902ec516c45307619708d3e780ae1.w5eKiLvhnLP8MtIf 取 w5eKiLvhnLP8MtIf 使用 + * @return Token + */ + public static String getToken(String apiKey, String apiSecret) { + // 缓存Token + String token = cache.getIfPresent(apiKey); + if (null != token) return token; + // 创建Token + Algorithm algorithm = Algorithm.HMAC256(apiSecret.getBytes(StandardCharsets.UTF_8)); + Map payload = new HashMap<>(); + payload.put("api_key", apiKey); + payload.put("exp", System.currentTimeMillis() + expireMillis); + payload.put("timestamp", Calendar.getInstance().getTimeInMillis()); + Map headerClaims = new HashMap<>(); + headerClaims.put("alg", "HS256"); + headerClaims.put("sign_type", "SIGN"); + token = JWT.create().withPayload(payload).withHeader(headerClaims).sign(algorithm); + cache.put(apiKey, token); + return token; + } + +} -- GitLab