Search code examples
javajwtjson-web-token

is there a way to parse claims from an expired JWT token?


If we try to parse an expired JWT, results in expired exception.

Is there a way to read claims even the JWT was expired.

Below is used to parse JWT in java:

Jwts.parser().setSigningKey(secret.getBytes()).parseClaimsJws(token).getBody();


Solution

  • JWT objects are Base64URL encoded. This means that you can always read headers and payload by manually Base64URL-decoding it. In this case you will simply ignore exp attribute.

    For instance you can do like this (I'm using Java8 built-in Base64 class, but you can use any external library, such as Apache Commons Codec):

    Base64.Decoder decoder = Base64.getUrlDecoder();
    String src = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImV4cCI6IjEzMDA4MTkzODAifQ.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.2GpoV9q_uguSg0Ku6peI5aZ2qBxO5qOA42zaS25gq_c";
    String[] parts = src.split("\\."); // Splitting header, payload and signature
    System.out.println("Headers: "+new String(decoder.decode(parts[0]))); // Header
    System.out.println("Payload: "+new String(decoder.decode(parts[1]))); // Payload
    

    and the output is:

    Headers: {"alg":"HS256","typ":"JWT","exp":"1300819380"}
    Payload: {"sub":"1234567890","name":"John Doe","admin":true}
    

    Please note also that the exp attribute is set to 1300819380, which corresponds to 16 january 2016.