When interacting with an external API, I might get an access token to use to authenticate to that API. That access token might have an expiration date. If I'm going to reuse that token to make a few API calls, at some point, the access token might be expired, and I would need to renew it.
Knowing if the token is expired helps a lot to know when to renew that access token.
if (jwt.isExpired(token)) {
token = await renewToken()
}
// make API call
function jwtIsExpired(token) {
const decoded = jwt.decode(token)
return decoded.exp < Date.now() / 1000
}
It's not very difficult, but it would be easier if provided by the library.
@aymericbouzy auth0/node-jsonwebtoken#tokenexpirederror
Thanks for pointing out that error type.
This doesn't seem to fit my use case though: I'm trying to know if a JWT is expired _without_ knowing the secret: I am not the issuer of the access token. This access token is provided by an external API. I want to know if it is expired as the _client_ (to save me from doing a request that will be rejected).
Maybe I shouldn't? Maybe I should send my request to the external API, wait for the response, read the 4xx error, identify that it is telling me the token is expired and _then_ request a new one?
What I've just described works of course, and is a third option to the first two I had given, but the DX and performance is poor compared to a synchronous isExpired() method.
I hope to have clarified what I'm looking for 馃檪
Most helpful comment
Thanks for pointing out that error type.
This doesn't seem to fit my use case though: I'm trying to know if a JWT is expired _without_ knowing the secret: I am not the issuer of the access token. This access token is provided by an external API. I want to know if it is expired as the _client_ (to save me from doing a request that will be rejected).
Maybe I shouldn't? Maybe I should send my request to the external API, wait for the response, read the 4xx error, identify that it is telling me the token is expired and _then_ request a new one?
What I've just described works of course, and is a third option to the first two I had given, but the DX and performance is poor compared to a synchronous
isExpired()method.I hope to have clarified what I'm looking for 馃檪