6

Let's say we have short-lived access token (15 minutes) and long-term refresh token (7 days).

When should we ask backend to refresh access token?

I see two options:

  1. After user logs in we start a countdown to automatically refresh token one minute before access token expires.
  2. We don't implement timer and we try to refresh access token ONLY if we get 401 response from backend.

In first option I see one advantage - if access token and refresh token will expired AND user stays on the page, not taking any action, he also doesn't send any http request than the timer still works and user is logged out automatically.

In second option - if access token and refresh token will expired user will be logged out ONLY if he will make some action on page for example: leave a page or make a http request. If he will stay on page he won't be logged out automatically.

What is a better implementation on frontend than?

Rocky3582
  • 573
  • 4
  • 7
  • 17

1 Answers1

6

I would recommend option 2 as your default behavior, since it will give you a resilient app. Every OAuth client should do this, since 401s can sometimes also be received for infrastructure reasons in some setups, eg token signing certificate renewal.

Option 1 is an optimization, if you want to reduce 401 responses from APIs. However it can lead to incorrectly developed clients and APIs if you are not careful. Personally I never use it.

Note that an expires_in field is returned with the access token but there is no equivalent field for the refresh token, so the client cannot detect when the user session will expire unless you develop a custom solution.

When coding API calls it is recommended to do this, as in this sample code of mine:

  • When a 401 is received try a token refresh
  • On success retry the API call - once only
  • On failure redirect the user to authenticate again

Out of interest there is an online version of the above app that allows you to test OAuth expiry events to see how this behaves - see my Quick Start page

Gary Archer
  • 22,534
  • 2
  • 12
  • 24