JWTUtils工具类

325 阅读1分钟
package com.boot.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.Map;

public class JWTUtils {

    // 秘钥,用于签名JWT
    private static final String SECRET_KEY = "your-secret-key";

    // 过期时间,例如设置为1天后
    private static final long EXPIRATION_TIME = 1000 * 60 * 60 * 24; // 1天

    /**
     * 生成JWT
     *
     * @return 生成的JWT字符串
     */
    public static String generateToken(Map<String, Object> claim, Integer uid) {
        return JWT.create()
                .withSubject(uid + "") //subject 主题(通常是用户ID)
                .withClaim("claims", claim) // 自定义载荷信息
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) // 设置过期时间
                .sign(Algorithm.HMAC256(SECRET_KEY)); // 使用HMAC256签名算法和SECRET_KEY
    }

    /**
     * 验证JWT并获取userId
     *
     * @param token JWT字符串
     * @return 解析出的userId,如果验证失败则抛出异常
     * @throws JWTVerificationException 验证失败异常
     */
    public static DecodedJWT parseToken(String token) throws JWTVerificationException {
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
        JWTVerifier verifier = JWT.require(algorithm).build();
        return verifier.verify(token);
    }

    /**
     * 获取JWT令牌的主题(通常是用户ID)
     *
     * @param token JWT令牌字符串
     * @return 主题(通常是用户ID)
     * @throws JWTDecodeException 如果令牌无效或已过期
     */
    public static String getSubject(String token) throws JWTDecodeException {
        DecodedJWT jwt = parseToken(token);
        return jwt.getSubject();
    }
}