Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Calling Secure APIs with Access Tokens | Securing and Extending Auth0 in React
Auth0 Authentication and Authorization in React Apps

bookCalling Secure APIs with Access Tokens

When you need to interact with protected APIs from your React app, you must ensure that only authenticated users can access sensitive resources. This is achieved through API authorization, which verifies the user's identity and checks their permissions before granting access. The central element in this process is the access token.

An access token is a credential issued by Auth0 after a user successfully authenticates. This token contains information about the user's identity and permissions, allowing your React app to prove to the API that the request comes from an authenticated user. APIs validate the access token before processing the request, ensuring that only authorized users can access protected endpoints.

To call a secure API from your React app, you first need to retrieve an access token using the useAuth0 hook. Once you have the token, you include it in the Authorization header of your API request. This enables the API to verify that the request is coming from an authenticated and authorized user.

Suppose you want to fetch a user's profile data from a protected API endpoint. You can use the getAccessTokenSilently method from the useAuth0 hook to obtain the access token without interrupting the user's experience. Then, you add the token to your fetch request as a Bearer token in the header. Here is how you might do this in your React component:

import React, { useEffect, useState } from "react";
import { useAuth0 } from "@auth0/auth0-react";

function ProfileData() {
  const { getAccessTokenSilently, isAuthenticated } = useAuth0();
  const [profile, setProfile] = useState(null);

  useEffect(() => {
    const fetchProfile = async () => {
      if (isAuthenticated) {
        const accessToken = await getAccessTokenSilently();
        const response = await fetch("https://api.example.com/profile", {
          headers: {
            Authorization: `Bearer ${accessToken}`
          }
        });
        const data = await response.json();
        setProfile(data);
      }
    };
    fetchProfile();
  }, [getAccessTokenSilently, isAuthenticated]);

  if (!profile) return <div>Loading...</div>;
  return (
    <div>
      <h2>Profile</h2>
      <pre>{JSON.stringify(profile, null, 2)}</pre>
    </div>
  );
}

export default ProfileData;

In this example, the access token is retrieved silently and automatically included in the API request. The API can then verify the token and respond with the user's profile data if the token is valid and the user has the required permissions.

Note
Definition

Scopes are strings included in an access token that specify the permissions granted to the token bearer. When requesting an access token, you can ask for specific scopes, such as read:profile or write:messages. The API checks these scopes to determine what actions the user is allowed to perform, enforcing fine-grained access control based on the scopes present in the token.

question mark

Which statement best describes the role of access tokens and scopes when calling a protected API?

Select the correct answer

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 5

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

bookCalling Secure APIs with Access Tokens

Desliza para mostrar el menú

When you need to interact with protected APIs from your React app, you must ensure that only authenticated users can access sensitive resources. This is achieved through API authorization, which verifies the user's identity and checks their permissions before granting access. The central element in this process is the access token.

An access token is a credential issued by Auth0 after a user successfully authenticates. This token contains information about the user's identity and permissions, allowing your React app to prove to the API that the request comes from an authenticated user. APIs validate the access token before processing the request, ensuring that only authorized users can access protected endpoints.

To call a secure API from your React app, you first need to retrieve an access token using the useAuth0 hook. Once you have the token, you include it in the Authorization header of your API request. This enables the API to verify that the request is coming from an authenticated and authorized user.

Suppose you want to fetch a user's profile data from a protected API endpoint. You can use the getAccessTokenSilently method from the useAuth0 hook to obtain the access token without interrupting the user's experience. Then, you add the token to your fetch request as a Bearer token in the header. Here is how you might do this in your React component:

import React, { useEffect, useState } from "react";
import { useAuth0 } from "@auth0/auth0-react";

function ProfileData() {
  const { getAccessTokenSilently, isAuthenticated } = useAuth0();
  const [profile, setProfile] = useState(null);

  useEffect(() => {
    const fetchProfile = async () => {
      if (isAuthenticated) {
        const accessToken = await getAccessTokenSilently();
        const response = await fetch("https://api.example.com/profile", {
          headers: {
            Authorization: `Bearer ${accessToken}`
          }
        });
        const data = await response.json();
        setProfile(data);
      }
    };
    fetchProfile();
  }, [getAccessTokenSilently, isAuthenticated]);

  if (!profile) return <div>Loading...</div>;
  return (
    <div>
      <h2>Profile</h2>
      <pre>{JSON.stringify(profile, null, 2)}</pre>
    </div>
  );
}

export default ProfileData;

In this example, the access token is retrieved silently and automatically included in the API request. The API can then verify the token and respond with the user's profile data if the token is valid and the user has the required permissions.

Note
Definition

Scopes are strings included in an access token that specify the permissions granted to the token bearer. When requesting an access token, you can ask for specific scopes, such as read:profile or write:messages. The API checks these scopes to determine what actions the user is allowed to perform, enforcing fine-grained access control based on the scopes present in the token.

question mark

Which statement best describes the role of access tokens and scopes when calling a protected API?

Select the correct answer

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 5
some-alt