Reputation: 6655
I am using JWT's to authenticate my API server. The JWT is issued by an external auth server (in this case keycloak) and have a typical expiration time of ~5 minutes (IIRC), the frontend should then use these tokens to make requests to the API.
I have been trying to check the expiry date of the token on the frontend, before making each request. If the token is expired, I use the refresh token to first get a new auth token then make the request.
The basic workflow is:
== Login == 1. Get Auth token 2. Store expiry (exp) date (this is in UTC seconds)
== API Request ==
1. Check expiry date (isExpired = expiryDate <= Math.floor(Date.now() / 1000)
)
2. If OK => make request
3. Otherwise, refresh auth token and redo request.
Is it bad practice to check the date like this? What is an alternative method to ensuring requests succeed?
I ask because I have seen problems on some machines where the expiration check always returns false
(it is not expired)...
Upvotes: 5
Views: 9534
Reputation: 1
I feel, a frontend check will be a good instead of making a request with expired token and do the refresh mechanism post that. I agree, the local time may differ. To make sure that it does work if we use UTC in token we can easily validate in any timeZone.
Upvotes: 0
Reputation: 11
The best way to handle that situation is that the front should only check if the expiry date set in the backend is expired or not. Usually the error return just like this {name: 'TokenExpiredError', message: 'jwt expired'}. If that is the case, then that's the time that you will make another login request.
Upvotes: 1
Reputation: 1844
The problem with relying with a frontend check is you have no control over the local time on the user's machine, which could be wrong.
A more robust way could be to make the request as usual and if the token has expired return an error message from the server. On each request, if the error message is received from the server, the client can then trigger the refresh process and then resubmit the original request with the new token.
Upvotes: 8