0

I've read a few articles which cover the set up for refresh tokens and JWT tokens

Is there a best practice in how/when to get the next JWT token.

In my head, there are a few different approaches. I will ignore authorisation for this post.

  1. Log in and authenticate
  2. On each server request, pull back a new JWT and refresh the cookie token

Or

  1. Log in and authenticate
  2. If the request to the server fails due to non-authenticated, then attempt to get a new token. If this is a success, repeat the original request, otherwise, assume not logged in

Another approach would be

  1. Log in and authenticate
  2. Have a polling task that executes every n minutes. Before the JWT expires, refresh and pull a new token

I am aware in software we have the ability to approach things in different ways based upon the problem we are trying to solve. However, it does feel that this must be something the software community have tried and tested and overall there is a default pattern?

1 Answer 1

2

A JWT can be read by the client (unless you have decided to encrypt it), so there is no need for trial and error (your second approach) or a specific polling job (your third approach).

Instead, the client can simply look at the expiry timestamp of its current token when it is about to send a request to the server:

  • If it has expired, or is about to expire within some short window (e.g. 30 seconds), request a new token
  • Otherwise, use the current token

(If you don't want to trust the client to read the JWT, you could encrypt it, and communicate the expiry timestamp separately when it is issued.)

This effectively makes the frequency of refreshes the decision of the authentication server: issue tokens lasting only 30 seconds, and the client will refresh on every request; issue tokens lasting 10 minutes, and the client will wait at least 9½ minutes before requesting a new one. This might even vary depending on the contents of the token, e.g. a token granting access to high-sensitivity information might have a particularly short lifetime.

The maximum time that can elapse between the token expiring and the client refreshing it is the lifetime of the refresh token. That lifetime represents the maximum idle time of the session - a refresh token lasting 1 hour means the user can login, go away for 59 minutes, and then click something, and still be logged in. When a new client token is issued, a new refresh token can also be issued, resetting the idle timer. (This is an explicit downside of refreshing on a timer - if the client gets a new token every 10 minutes regardless of activity, you need some other way to measure idle time, or the user will stay logged in forever.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.