Skip to content
Advertisement

How to check if a JWT Token has expired without throw exceptions?

I’m developing a Java application (using Spring Boot) and I need some help: This application receives as input a JWT token which I process in a method. The method for now is the following:

private UsernamePasswordAuthenticationToken myMethod(HttpServletRequest request) {
    
    // Code that gets the 'token' String

    try{
    
    Map<String, String> registry = ((Map<String, String>) (token.getBody().get("registry")));
    String sub = ((String) (parsedToken.getBody().get("sub")));


    UsernamePasswordAuthenticationToken finalToken = new UsernamePasswordAuthenticationToken(sub, null, null);
                            
            
    return finalToken; 

            
    } catch (ExpiredJwtException exception) { // Only here I have the certainty that the token has expired!
            // Code that handles the exception
    }

}

However, I need to implement a logic that must check in several places whether the token obtained has expired or not, without running this method every time. The only way I have to know if token has expired is the exception raised by ExpiredJwtException.

Is there any way to know if the token has expired without going through the catched exception? For example, it would be very useful if there was a “token” class that has an .isExpired attribute, or something like that.

I don’t want to go into handling the exception because it means that I would always depend on the (long) code of the try block every time I need to check if a token has expired or not, and I don’t want it to be.

Advertisement

Answer

If you use a different JWT library, you can do it easily enough. The auth0 JWT library has methods to parse and, optionally, verify the token:

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;


DecodedJWT jwt = JWT.decode(token);
if( jwt.getExpiresAt().before(new Date())) {
    System.out.println("token is expired");
}

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement