Calling 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.
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.
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo
Incrível!
Completion taxa melhorada para 9.09
Calling Secure APIs with Access Tokens
Deslize para mostrar o menu
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.
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.
Obrigado pelo seu feedback!