React: Token Renewal
This tutorial demonstrates how to add automatic Access Token renewal to a React application with Auth0. We recommend you to Log in to follow this quickstart with examples configured for your account.
I want to explore a sample app2 minutes
Get a sample configured with your account settings or check it out on Github.
For security, keep the expiry time of a user's Access Token short.
When you create an API in the Auth0 dashboard, the default expiry time for browser flows is 7200 seconds (2 hours).
This short expiry time is good for security, but can affect user experience. To improve user experience, provide a way for your users to automatically get a new Access Token and keep their client-side session alive. You can do this with Silent Authentication.
Add Token Renewal
Auth service, we already have a method which calls the
checkSession method from auth0.js. If the renewal is successful, use the existing
setSession method to set new tokens in local storage.
The Access Token should be renewed when it expires. In this tutorial, we'll make sure it automatically reviews when the token expires. The expiry time of the token is stored in the Auth service
Define a timing mechanism for renewing the token.
Auth service, add a property called
tokenRenewalTimeout which refers to the
Add a method called
scheduleRenewal to set up the time when the authentication is silently renewed. The method subtracts the current time from the Access Token's expiry time and calculates delay. The
setTimeout call uses the calculated delay and makes a call to
setTimeout call call is assigned to the
tokenRenewalTimeout property. When the user logs out, the timeout is cleared.
You can now include a call to the
scheduleRenewal method in the
To schedule renewing the tokens when the page is refreshed, in the constructor of the
Auth service, add a call to the
Since client-side sessions should not be renewed after the user logs out, call
clearTimeout in the
logout method to cancel the renewal.
If you're having problems with token renewal (for example, you get the
login_required error), make sure you're not using Auth0 dev keys for social login. You must use your own social authentication keys.