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; } }