React Calling an API

Sample Project

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

System Requirements
  • React 15.5
Show requirements

It's likely that your single page app will need to consume resources from a data API. Since you are adding authentication to your app, presumably you need to limit access to these resources such that they are only accessible by an authenticated user who is authorized to retrieve them. Auth0 provides API Authorization to accomplish this.

This tutorial will guide you through how to make calls from your application to your data API to access protected resources. It does not, however, cover how to add protection to your API itself. For instructions on protecting your API, please follow the Backend/API quickstart documentation specific to your situation.

Create a Resource Server (API)

In the APIs section of the Auth0 Dashboard, click the Create API button. Provide a Name and Identifier for your API and be sure to choose the RS256 signing algorithm. The identifier you set will later be used as the audience when configuring your auth0.WebAuth instance.

Create API

Add a Scope

When an access_token is received after a user authenticates in your app, it is simply an indication that they have proven their identity. By default, however, the access_token does not contain any authorization information. To properly limit access to your resources based on authorization, you must use scopes.

In the settings area for your API within the Auth0 dashboard, navigate to the Scopes tab. Add any scopes necessary to limit access to your API resources. While the naming of the scopes is at your discretion, a common pattern is to use <action>:<resource>. The example here will use a read:messages scope.

create scope

Set the Audience and Scope in auth0.WebAuth

Pass the API identifier for your newly created API as the audience value in your auth0.WebAuth instance. Additionally, pass any of your newly created scopes to the scope key.

// src/Auth/Auth.js

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

Checkpoint: Try logging into your application again to take note of how the access_token differs from before. Instead of being an opaque token, it is now a JSON Web Token which has a payload that contains your API identifier as an audience and any scopes you've requested.

By default, any user on any client can ask for any scope defined in the scopes configuration area. You can implement access policies to limit this behaviour via Rules.

Send Authenticated HTTP Requests

To access secured resources from your API, the authenticated user's access_token needs to be included in requests that are sent to it. This is typically accomplished either by sending the access_token in an Authorization header using the Bearer scheme or by storing the token in a cookie so that it is included in all requests to your server. These example will focus on the former implementation, but both approaches are valid.

Attaching the user's access_token as an Authorization header to HTTP calls can be done on a one-off basis by adding the header as an option to your requests. This example demonstrates how to do so with axios but you are free to use whichever HTTP client you like.

// src/Ping/Ping.js

import React, { Component } from 'react';
import axios from 'axios';

// ...
class Ping extends Component {
  // ...
  securedPing() {
    const { getAccessToken } = this.props.auth;
    const API_URL = 'http://<your-url>.com/api';
    const headers = { 'Authorization': `Bearer ${getAccessToken()}`}
    axios.get(`${API_URL}/private`, { headers })
      .then(response => this.setState({ message: response.data.message }))
      .catch(error => this.setState({ message: error.message }));
  }
}

export default Ping;

How Do I Protect my API Resources?

To restrict access to the resources served by your API, a check needs to be made to determine whether the incoming request contains valid authorization information. When you implement Auth0 in your client-side application and data API, that authorization information is the access_token issued for your user. This token must be checked against the JSON Web Key Set (JWKS) for your Auth0 account to verify that it is valid.

The exact way in which access_token verification is implemented on your server will vary between languages and frameworks; however, a common pattern involves placing the token verification logic in a middleware function. If the access_token is valid, the request should proceed. If it is invalid, the request should be rejected with a 401 Unauthorized error.

The downloadable sample linked above demonstrates how to accomplish this implementation using Node.js with the Express framework. For instructions on how to implement API protection for the specific server-side technology you are using, see the Backend/API quickstart documentation.

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