Auth0 Automatic Token Renewal

Renew clients auth token instead of having the client reauthenticate

Fri, 02 Nov 2018

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

  1. Sign into you’re Auth0 account
  2. Click Applications on the side menu
  3. Click the name of your application
  4. Click Settings
  5. Scroll down to Allowed Web Origins
  6. 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

  1. 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;
  1. 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()
    }
  2. The login method just needs to make a call to the scheduleRenewal function

    login() {
    this.auth0.authorize();
    this.scheduleRenewal();
    }
  3. 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("/")
    }
  4. In our setSession function we add a call for schedule renewal

    setSession(authResult) {
    	....
    this.scheduleRenewal()
    }
  5. Create a new function called renewToken

    renewToken() {
    this.auth0.checkSession({}, (err, result) => {
      if (err) {
        console.log(err);
      } else {
        this.setSession(result);
      }
    });
    }
  6. 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!

Loading...
Edward Beazer

Edward Beazer - I just like to build shit. Sometimes I get stuck for hours, even days while trying to figure out how to solve an issue or implement a new feature. Hope my tips and tutorials can save you some time.