Blame view

JwtUtil.java 2.42 KB
涂亚平 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
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;
        }
    }
}