5

I am looking for a mechanism for renewal of jwt token based on authenticity of expired token. here is my what i tried

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();
    }

}

As you can see in verification part renewSignedToken i'm able to get payload but i want to add check if the token has vaild signature and claims are not altered.

Les Hazlewood
  • 18,480
  • 13
  • 68
  • 76
Rajat
  • 2,467
  • 2
  • 29
  • 38

0 Answers0