JavaScript Calling an API

Sample Project

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

Most single-page apps use resources from data APIs. You may want to restrict access to those resources, so that only authenticated users with sufficient privileges can access them. Auth0 lets you manage access to these resources using API Authorization.

This tutorial shows you how to access protected resources in your API.

This tutorial does not show you how to add protection to your API. Read the Backend/API quickstart documentation for instructions on how to protect your API.

Create a Resource Server (API)

In the APIs section of the Auth0 dashboard, click Create API. Provide a name and an identifier for your API. You will use the identifier later when you're configuring your Javascript Auth0 client instance. For Signing Algorithm, select RS256.

Create API

Add a Scope

By default, the access token does not contain any authorization information. To limit access to your resources based on authorization, you must use scopes. Read more about scopes in the scopes documentation.

In the Auth0 dashboard, in the APIs section, click Scopes. Add any scopes you need to limit access to your API resources.

You can give any names to your scopes. A common pattern is <action>:<resource>. The example below uses the name read:messages for a scope.

create scope

Set the Audience and Scope in auth0.WebAuth

In your auth0.WebAuth instance, enter your API identifier as the value for audience. Add your scopes to the scope key.

// app.js

var webAuth = new auth0.WebAuth({
  // ...
  audience: '{YOUR_API_IDENTIFIER}',
  scope: 'openid profile read:messages'
});

Checkpoint: Try to log in to your application again. Look at how the access_token differs from before. It is no longer an opaque token. It is now a JSON Web Token with a payload that contains your API identifier as the value for audience, and the scopes you created. Read more about this token in the JSON Web Tokens documentation.

By default, any user can ask for any scope you defined. You can implement access policies to limit this behavior using Rules.

Configure a Custom XHR Request

To give the authenticated user access to secured resources in your API, include the user's access token in the requests you send to your API. There are two common ways to do this.

  • Store the access token in a cookie. The access token is then included in all requests.
  • Send access_token in the Authorization header using the Bearer scheme.

The examples below use the Bearer scheme.

To attach the user's access token to HTTP calls as an Authorization header, add the header as an option to your requests.

We recommend you implement a custom function which adds the header automatically.

Create a new function called callAPI. The function wraps an XHR request with the user's access token included as the Authorization header.

// app.js

var apiUrl = 'http://localhost:3001/api';

// ...
function callAPI(endpoint, secured) {
  var url = apiUrl + endpoint;
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url);
  if (secured) {
    xhr.setRequestHeader(
      'Authorization',
      'Bearer ' + localStorage.getItem('access_token')
    );
  }
  xhr.onload = function() {
    if (xhr.status == 200) {
      // update message
      document.querySelector('#ping-view h2').innerHTML = JSON.parse(
        xhr.responseText
      ).message;
    } else {
      alert('Request failed: ' + xhr.statusText);
    }
  };
  xhr.send();
}

Protect Your API Resources

To restrict access to the resources served by your API, check the incoming requests for valid authorization information. The authorization information is in the access token created for the user. To see if the token is valid, check it against the JSON Web Key Set (JWKS) for your Auth0 account. To learn more about validating access tokens, read the Verify Access Tokens tutorial.

In each language and framework, you verify the access token differently. Typically, you use a middleware function to verify the token. If the token is valid, the request proceeds and the user gets access to resources in your API. If the token is invalid, the request is rejected with a 401 Unauthorized error.

The sample project shows how to implement this functionality using Node.js with the Express framework. To learn how to implement API protection for your server-side technology, see the Backend/API quickstart documentation.

Previous Tutorial
2. User Profile
Next Tutorial
4. Authorization
Use Auth0 for FREECreate free Account