Node-jsonwebtoken: Feature request : jwt.isExpired(token)

Created on 2 Mar 2020  路  2Comments  路  Source: auth0/node-jsonwebtoken

Describe the problem you'd like to have solved

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.

Describe the ideal solution

if (jwt.isExpired(token)) {
    token = await renewToken()
}
// make API call

Alternatives and current work-arounds

  1. I can decide to acquire a fresh access token before any API call. It's simple, but not very efficient.
  2. I can implement that function myself :
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.

Most helpful comment

@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 馃檪

All 2 comments

@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 馃檪

Was this page helpful?
0 / 5 - 0 ratings