JavaScript Authorization

Sample Project

Download a sample project specific to this tutorial configured with your Auth0 API Keys.

This tutorial shows you how to control authorization in your client-side single page application.

Access Control in Single Page Applications

Access control is the control over what different users can see in your application and which routes they can access. With Auth0, you can implement access control by using scopes granted to users.

To set up access control in your application, define the following restrictions:

  • The data from an API can only be returned if the user is authorized to access it.
  • The user can access specific routes and UI elements in your application only if they have the appropriate access level.

The previous step used the read:messages scope for accessing API resources. This scope indicates that the user can only view the data. You can consider users with this scope regular users. If you want to give some users permission to edit the data, you can add the write:messages scope.

Read about naming scopes and mapping them to access levels in the Scopes documentation. To learn more about custom scope claims, follow the User profile claims and scope tutorial.

Determine a User's Scopes

You can use scopes to make decisions about the behavior of your application's interface.

You can specify which scopes you want to request at the beginning of the login process.

If a scope you requested is available to the user, their access token receives a scope claim in the payload. The value of this claim is a string with all the granted scopes, but your application must treat the access token as opaque and must not decode it. This means that you cannot read the access token to access the scopes.

To get the scopes, you can use the value of the scope parameter that comes back after authentication. This parameter is a string containing all the scopes granted to the user, separated by spaces. This parameter will be populated only if the scopes granted to the user are different than those you requested.

To see which scopes are granted to the user, check for the value of authResult.scope. If there is no value for authResult.scope, all the requested scopes were granted.

Handle Scopes in the app.js File

Adjust your app.js file, so it uses a local member with any scopes you want to request when users log in. Use this member in your instance of the auth0.WebAuth object.

// app.js

var requestedScopes = 'openid profile read:messages write:messages';

var auth0 = new auth0.WebAuth({
  // ...
  scope: requestedScopes
});

Add a setSession method to save the scopes granted to the user into browser storage.

First, check for the scopes in the scope key from authResult. If it's not empty, the user was granted a different set of scopes than the one the application requested, so you need to use the ones in authResult.scope.

If it's empty, all the scopes requested were granted, so you can use the values from variable that stores the requested scopes.

// app.js

function setSession(authResult) {
  
  const scopes = authResult.scope || requestedScopes || '';

  // ...
  localStorage.setItem('scopes', JSON.stringify(scopes));
}

Add a function called userHasScopes that checks for scopes in local storage. Add an array of strings to the method. Check if the array of scopes saved in local storage contains those values. You can use this method to conditionally hide and show UI elements to the user and to limit route access.

// app.js

function userHasScopes(scopes) {
  var savedScopes = JSON.parse(localStorage.getItem('scopes'));
  if (!savedScopes) return false;
  var grantedScopes = savedScopes.split(' ');
  for (var i = 0; i < scopes.length; i++) {
    if (grantedScopes.indexOf(scopes[i]) < 0) {
      return false;
    }
  }
  return true;
}

Conditionally Display UI Elements

You can use the userHasScopes function with the isAuthenticated function to show and hide certain UI elements.

// app.js

// ...
function displayButtons() {
  // ...
  if (!isAuthenticated || !userHasScopes(['write:messages'])) {
    adminViewBtn.style.display = 'none';
  } else {
    adminViewBtn.style.display = 'inline-block';
  }
}

Protect Client-Side Routes

You may want to give access to some routes in your application only to authenticated users. You can check if the user is authenticated with the userHasScopes function.

Depending on the routing library you use, you apply the userHasScopes function differently.

Some routing libraries provide hooks which run a function before the route is activated. This kind of hook might be called something like beforeEnter or onEnter. This is a good place to run the userHasScopes function to check whether the user has the scopes required to enter the route.

Conditionally Assign Scopes to Users

By default, when you register scopes in your API settings, all the scopes are immediately available and any user can request them. If you want to handle access control, you need to create policies for deciding which users can get which scopes.

You can use Rules to create access policies. See the Rules documentation to learn how to use Rules to create scope policies.

Considerations for Client-Side Access Control

For the access control on the client-side, the scope values that you get in local storage are only a clue that the user has those scopes. The user could manually adjust the scopes in local storage to access routes they shouldn't have access to.

On the other hand, to access data on your server, the user needs a valid access token. Any attempt to modify an access token invalidates the token. If a user tries to edit the payload of their access token to include different scopes, the token will lose its integrity and become useless.

You should not store your sensitive data client-side. Make sure you always request it from the server. Even if users manually navigate to a page they are not authorized to see, they will not get the relevant data from the server and your application will still be secure.

Previous Tutorial
3. Calling an API
Next Tutorial
5. Token Renewal
Use Auth0 for FREECreate free Account