| package com.oep.backend.utils; |
| |
| import io.jsonwebtoken.Claims; |
| import io.jsonwebtoken.JwtBuilder; |
| import io.jsonwebtoken.Jwts; |
| import io.jsonwebtoken.security.SecureDigestAlgorithm; |
| import org.springframework.stereotype.Component; |
| |
| import javax.crypto.SecretKey; |
| import javax.crypto.spec.SecretKeySpec; |
| import java.util.Base64; |
| import java.util.Date; |
| import java.util.UUID; |
| |
| @Component |
| public class JwtUtil { |
| public static final long JWT_TTL = 60 * 60 * 1000L * 24 * 14; |
| public static final String JWT_KEY = "SDFGjhdsfalshdfHFdsjkdsfds12jqyhy3wppwpuqt31afasdfac2h0y01j02q08yi15"; |
| |
| private final static SecureDigestAlgorithm<SecretKey, SecretKey> signatureAlgorithm = Jwts.SIG.HS256; |
| public static String getUUID() { |
| return UUID.randomUUID().toString().replaceAll("-", ""); |
| } |
| |
| public static String createJWT(String subject) { |
| JwtBuilder builder = getJwtBuilder(subject, null, getUUID()); |
| return builder.compact(); |
| } |
| |
| private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) { |
| SecretKey secretKey = generalKey(); |
| long nowMillis = System.currentTimeMillis(); |
| Date now = new Date(nowMillis); |
| if (ttlMillis == null) { |
| ttlMillis = JwtUtil.JWT_TTL; |
| } |
| |
| long expMillis = nowMillis + ttlMillis; |
| Date expDate = new Date(expMillis); |
| return Jwts.builder() |
| .id(uuid) |
| .subject(subject) |
| .issuer("sg") |
| .issuedAt(now) |
| .signWith(secretKey, signatureAlgorithm) |
| .expiration(expDate); |
| } |
| |
| public static SecretKey generalKey() { |
| byte[] encodeKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY); |
| return new SecretKeySpec(encodeKey, 0, encodeKey.length, "HmacSHA256"); |
| } |
| |
| public static Claims parseJWT(String jwt) throws Exception { |
| SecretKey secretKey = generalKey(); |
| return Jwts.parser() |
| .verifyWith(secretKey) |
| .build() |
| .parseSignedClaims(jwt) |
| .getPayload(); |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律