JwtUtil

public class JwtUtil {

    @Value("${jwt.secret}")
    private String secret;

    private static final String UID_CLAIM = "uid";
    private static final String CREATE_TIME = "createTime";

    /**
     * 创建生成token
     */
    public String createToken(Long uid) {
        return JWT.create()
                // 创建claim保存用户信息
                .withClaim(UID_CLAIM, uid)
                .withClaim(CREATE_TIME, new Date())
                // 创建签名
                .sign(Algorithm.HMAC256(secret));
    }

    /**
     * 解析token
     */
    public Map<String, Claim> verifyToken(String token) {
        if (token.isEmpty()) {
            return null;
        }
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaims();
        } catch (Exception e) {
            log.error("decode error, token: {}", token, e);
        }
        return null;
    }

    /**
     * 根据token获取uid
     */
    public Long getUidOrNull (String token) {
        return Optional.ofNullable(verifyToken(token))
                .map(map -> map.get(UID_CLAIM))
                .map(Claim::asLong)
                .orElse(null);
    }

    /**
     * 获取token的到期时间(什么时候到期)
     */
    public String getTimeOfExpiration(String token) {
        return Optional.of(JWT.decode(token))
                .map(Payload::getExpiresAt)
                .map(h -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(h))
                .orElse(null);
    }

    /**
     * 获取token的过期时间(多长时间到期)
     */
    public Long getExpireTime(String token) {
        return Optional.of(JWT.decode(token))
                .map(Payload::getExpiresAt)
                .map(Date::getTime)
                .orElse(null);
    }

    /**
     * 生成key
     */
    public SecretKey generalKey() {
        byte[] encodeKey = Base64.getDecoder().decode(UID_CLAIM);
        return new SecretKeySpec(encodeKey, 0, encodeKey.length, "AES");
    }
}