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

If we try to parse expired JWT , you will get an expired exception.

Is there a way to read statements even if the JWT has expired. .

Below is used to parse JWT in java:

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

+6
source share
2 answers

JWT objects are encoded by Base64URL. This means that you can always read the headers and payload manually using Base64URL decoding. In this case, you simply ignore the exp attribute.

For example, you can do this (I use the 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 output:

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

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

+7
source

There is a better approach for this. if you see a JWT exception handler object, for example. ExpiredJwtException, the expection object itself contains the following: header, claims, and message

therefore, statements can be easily retrieved through this object, i.e. e.getClaims().getId() , where e is an ExpiredJwtException object.

ExpiredJwtException consturct is as follows: -

 public ExpiredJwtException(Header header, Claims claims, String message) { super(header, claims, message); } 

Example: -

  try{ // executable code }catch(ExpiredJwtException e){ System.out.println("token expired for id : " + e.getClaims().getId()); } 
+7
source

All Articles