首页 > 解决方案 > 如何确保过期的 JWT 令牌完好无损

问题描述

我正在寻找一种基于过期令牌的真实性来更新 jwt 令牌的机制。这是我的尝试

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import constants.AppConstants;

import java.io.UnsupportedEncodingException;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

public class JwtUtil {

    private static JWTVerifier verifier;
    private static String secret = AppConstants.JWT_KEY;

    static {

        Algorithm algorithm = null;
        try {
            algorithm = Algorithm.HMAC256(secret);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        verifier = JWT.require(algorithm)
                .withIssuer("Issuer")
                .build();
    }

    public static String getSignedToken(Long userId) {

        Algorithm algorithm = null;
        try {
            algorithm = Algorithm.HMAC256(secret);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return JWT.create()
                .withIssuer("Issuer")
                .withIssuedAt(Date.from(
                        ZonedDateTime.now(ZoneId.systemDefault()).toInstant()
                ))
                .withClaim("userId", userId)
                .withExpiresAt(Date.from(ZonedDateTime.now(
                        ZoneId.systemDefault()).plusMinutes(10).toInstant()
                ))
                .sign(algorithm);
    }

    public static String renewSignedToken(String oldToken) throws JWTVerificationException{
        DecodedJWT jwt = JWT.decode(oldToken);
        Long userId = jwt.getClaim("userId").asLong();
        return getSignedToken(userId);
    }

    public static Long verifyToken(String token) throws TokenExpiredException{
        DecodedJWT jwt = verifier.verify(token);
        return jwt.getClaim("userId").asLong();
    }

}

正如您在验证部分 renewSignedToken 中看到的那样,我能够获取有效负载,但我想添加检查令牌是否具有有效签名并且声明未更改。

标签: javajwtauth0

解决方案


推荐阅读