JwtUtil.java 2.42 KB
package com.subsidy.util;

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;

/**
 * <p>
 *  Token工具
 * </p>
 *
 * @author DengMin
 * @since 2021/4/14
 */
public class JwtUtil {

    private static Long EXPIRE_TIME = 24 * 60 * 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<String, Claim> getClaims(String token) {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        JWTVerifier verifier = JWT.require(algorithm).build();
        Map<String, Claim> 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;
        }
    }
}