From 051dd08ca22eee3aab167764a57d72c76e33071a Mon Sep 17 00:00:00 2001 From: tuyp Date: Thu, 8 May 2025 14:05:30 +0800 Subject: [PATCH] jwt工具类 --- src/main/java/com/template/utils/JwtUtil.java | 97 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 src/main/java/com/template/utils/JwtUtil.java diff --git a/src/main/java/com/template/utils/JwtUtil.java b/src/main/java/com/template/utils/JwtUtil.java new file mode 100644 index 0000000..d0a00c1 --- /dev/null +++ b/src/main/java/com/template/utils/JwtUtil.java @@ -0,0 +1,97 @@ +package com.template.utils; + +import com.auth0.jwt.JWT; +import com.auth0.jwt.JWTVerifier; +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.interfaces.Claim; + +import java.util.Date; +import java.util.Map; + +/** + *

+ * Token工具 + *

+ * + * @author DengMin + * @since 2021/4/14 + */ +public class JwtUtil { + +// 半小时 + private static Long EXPIRE_TIME = 30 * 60 * 1000L; + + private static String SECRET = "PBKDF2SHA256:64000:18:24:N:GFHZ6Y0PTEUDYCJI3K6SOOXWYEKPOZED:WBWFJMX5DF252E0HR3BF3P/D"; + + /** + * 生成Token + * @param id + * @return + */ + public static String generateToken(Long id, String type) { + Date expireDate = new Date(System.currentTimeMillis() + EXPIRE_TIME); + return JWT.create() + .withClaim("id", id) + .withClaim("type", type) + .withAudience() + .withExpiresAt(expireDate) + .withIssuedAt(new Date()) + .sign(Algorithm.HMAC256(SECRET)); + } + + /** + * 检验token是否正确 + * @param token + * @return + */ + public static boolean verifyToken(String token) { + try { + Algorithm algorithm = Algorithm.HMAC256(SECRET); + JWTVerifier verifier = JWT.require(algorithm).build(); + verifier.verify(token); + return true; + } catch (Exception e) { + return false; + } + } + + /** + * 获取用户自定义Claim集合 + * @param token + * @return + */ + public static Map getClaims(String token) { + Algorithm algorithm = Algorithm.HMAC256(SECRET); + JWTVerifier verifier = JWT.require(algorithm).build(); + Map claims = verifier.verify(token).getClaims(); + return claims; + } + + /** + * 获取过期时间 + * @param token + * @return + */ + public static Date getExpiresAt(String token) { + Algorithm algorithm = Algorithm.HMAC256(SECRET); + return JWT + .require(algorithm) + .build() + .verify(token) + .getExpiresAt(); + } + + /** + * 验证token是否失效 + * @param token + * @return true: 过期, false: 没过期 + */ + public static boolean isExpired(String token) { + try { + final Date expiration = getExpiresAt(token); + return expiration.before(new Date()); + } catch (Exception e) { + return true; + } + } +} -- libgit2 0.25.0