jQuery: Token Renewal

View on Github

jQuery: Token Renewal

Gravatar for andres.aguiar@auth0.com
By Andres Aguiar
Auth0

This tutorial demonstrates how to add automatic Access Token renewal to a jQuery application with Auth0. We recommend you to Log in to follow this quickstart with examples configured for your account.

I want to integrate with my app

15 minutes
  1. Token Lifetime
  2. Add Token Renewal
Or

I want to explore a sample app

2 minutes

Get a sample configured with your account settings or check it on Github.

View on Github
System requirements: jQuery 3.2.1

Token Lifetime

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.

You can control the expiry time of an Access Token from the APIs section. You can control the expiry time of an ID Token from the Applications section. These settings are independent.

Add Token Renewal

To the app.js file, add a function that calls the checkSession method from auth0.js. If the renewal is successful, use the existing setSession method to set the new tokens in local storage.

// app.js

function renewToken() {
  webAuth.checkSession({},
    function(err, result) {
      if (err) {
        console.log(err);
      } else {
        setSession(result);
      }
    }
  );
}

The access should be renewed when it expires. In this tutorial, the expiry time of the token is stored in local storage as expires_at.

You can define any timing mechanism you want. You can choose any library that handles timers. This example shows how to use a simple setTimeout call.

To the app.js file, add a variable called tokenRenewalTimeout. The variable refers to the setTimeout call used to schedule the renewal. Next, add a function called scheduleRenewal to set up the time when authentication is silently renewed.

The function 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 renewToken.

The setTimeout call is assigned to the tokenRenewalTimeout property. When the user logs out, the timeout is cleared.

// app.js

var tokenRenewalTimeout;
// ...
function scheduleRenewal() {
  var expiresAt = JSON.parse(localStorage.getItem('expires_at'));
  var delay = expiresAt - Date.now();
  if (delay > 0) {
    tokenRenewalTimeout = setTimeout(function() {
      renewToken();
    }, delay);
  }
}

You can now include a call to the scheduleRenewal function in the setSession function.

// app.js

// ...
function setSession(authResult) {
  // Set the time that the Access Token will expire at
  var expiresAt = JSON.stringify(
    authResult.expiresIn * 1000 + new Date().getTime()
  );
  localStorage.setItem('access_token', authResult.accessToken);
  localStorage.setItem('id_token', authResult.idToken);
  localStorage.setItem('expires_at', expiresAt);
  scheduleRenewal();
}

To schedule renewing the tokens when the page is refreshed, add a call to the scheduleRenewal function immediately when the page loads.

// app.js

window.addEventListener('load', function() {
  // ...
  scheduleRenewal();
});

Since client-side sessions should not be renewed after the user logs out, use clearTimeout in the logout method to cancel the renewal.

// app.js

function logout() {
  // ...
  clearTimeout(tokenRenewalTimeout);
}

Troubleshooting

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.

Use Auth0 for FREECreate free Account