Reputation: 1701
I need to check JWT token before sending it in request. But I not generated this token, I just reseived it by authorization, than, I have no secret for it.
I use io.jsonwebtoken.jjwt
library.
How to check token expiration time with this library?
Upvotes: 6
Views: 9298
Reputation: 4731
You do not need the secret to read the token. The secret is only required to ensure that the token was not modified. From what it looks like, however, the library, ensure you can not skip the signature check. So we need to trick it.
Accessing the Expiration while ignoring the Signature
A JWT consists of three parts, base64 encoded and separated by dots: Header.Body.Signature
If we remove the signature, there is nothing the library can check against. We must, however, also access the raw body , as signatureless claims are not supported.
var signedToken = "eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9...";
var tokenOnly = signedToken.substring(0, signedToken.lastIndexOf('.') + 1);
var expiration = ((Claims)Jwts.parser().parse(tokenOnly).getBody()).getExpiration();
However, without verifying the signature, you will not know if someone modified the token. I can not stress this enough: Never rely on any token information if you can not verify the signature.
How to do it better
Have a look at asymmetric algorithms (the RS, ES and PS family). This allows an issuer to generate JWTs with a private key and anyone with the corresponding public key can verify that the token is valid. This way you can validate and access the claims you want with the assurance that they where issued by an issuer you trust and that they where not modified in any way.
Upvotes: 7