Auth0 Automatic Token Renewal
Renew clients auth token instead of having the client reauthenticate
By default the normal timeout for the Auth0 web tokens is 36000 seconds or 5 hours. Depending on the kind of application you create you may want to have the tokens renew themselves to keep the user logged in indefinitely.
Auth0 Dashboard
In order to schedule token renewals for your application we need to add in a new web origin. Web Origins allow a url to make cross-origin authentication attempts. The steps to do that is as follows
- Sign into you’re Auth0 account
- Click Applications on the side menu
- Click the name of your application
- Click Settings
- Scroll down to Allowed Web Origins
- Enter your applications URL.
I would enter your development and production url into the list. For example, “http://localhost:8000” or “https://myapp.com”.
Auth0 File
- There is only a couple of changes we need to make in our Auth.js file to get token renewals going. After you instantiate your WebAuth add a tokenRenewalTimeout
auth0 = new auth0.WebAuth({
...
});
tokenRenewalTimeout;
-
Next up in is the constructor. We just want to add the scheduleRenewal function to our constructor.
constructor() { this.login = this.login.bind(this); this.logout = this.logout.bind(this); this.handleAuthentication = this.handleAuthentication.bind(this); this.isAuthenticated = this.isAuthenticated.bind(this); this.getAccessToken = this.getAccessToken.bind(this); this.scheduleRenewal() }
-
The login method just needs to make a call to the scheduleRenewal function
login() { this.auth0.authorize(); this.scheduleRenewal(); }
-
The logout method needs to clear our timer for the token renewal
logout() { localStorage.removeItem('access_token'); localStorage.removeItem('id_token'); localStorage.removeItem('expires_at'); localStorage.removeItem('user'); clearTimeout(this.tokenRenewalTimeout); history.replace("/") }
-
In our setSession function we add a call for schedule renewal
setSession(authResult) { .... this.scheduleRenewal() }
-
Create a new function called renewToken
renewToken() { this.auth0.checkSession({}, (err, result) => { if (err) { console.log(err); } else { this.setSession(result); } }); }
-
The last step is to schedule our renewal. Create another new function named scheduleRenewal
scheduleRenewal() { if (typeof window !== 'undefined') { const expiresAt = JSON.parse(localStorage.getItem('expires_at')); const delay = expiresAt - Date.now(); if (delay > 0) { this.tokenRenewalTimeout = setTimeout(() => { this.renewToken(); }, delay); } } }
Whenever a user logs in Auth0 will set a new timer equal to the expiration time of the users token. When the expiration time comes Auth0 will attempt to renew the token. If successful, the user won’t even know anything happened!