Skip to main content

How to Get an Access Token with MSAL React

· 11 min read
Jagdish Kumawat
Founder @ Dewiride

Signing someone in is half the job. To call an API for them, a React app needs an access token for that API, and MSAL, Microsoft's sign-in library, gets it in one call. This guide shows the pattern Microsoft recommends, silent first and interactive only when needed, and a live run of where each token came from.

Syntax​

Syntax
try {
const result = await instance.acquireTokenSilent({ scopes: [<scope>], account: <account> });
// use result.accessToken
} catch (error) {
if (error instanceof InteractionRequiredAuthError) {
await instance.acquireTokenRedirect({ scopes: [<scope>], account: <account> });
}
}
PartWhat to put there
instanceThe PublicClientApplication, which useMsal() returns in any component inside MsalProvider
<scope>The full scope of the API, such as api://<API client ID>/access_as_user. All scopes in one request must belong to the same API
<account>The signed-in account the token is for: accounts[0] from useMsal() when one person signs in
resultAn AuthenticationResult: accessToken, the scopes it grants, expiresOn and fromCache, among others
InteractionRequiredAuthErrorWhat MSAL throws when it can't get the token without the person, for example to consent or to sign in again

MSAL's documentation describes the rule: Every time you need an access token you should call acquireTokenSilent and if this fails call an interactive API instead. The silent call will look for a valid token in the cache, and if it is close to expiring or does not exist, will automatically try to refresh it for you using the cached refresh token.

The Example​

The example adds a Get an access token button to a Next.js app that already signs people in with MSAL React (How to Sign Users In to a Next.js App with MSAL React). The button asks for a token for an API registered as Dewiride Service Desk API, scope access_as_user, and shows what came back, never the token itself.

The app's registration lists the permission, and the API pre-authorizes the app, so nobody is asked to consent (How to Add an API Permission to an App Registration in Microsoft Entra ID, How to Pre-Authorize a Client Application for Your API in Microsoft Entra ID).

Prerequisites​

  • Your API's full scope, such as api://<API client ID>/access_as_user, from the API's Expose an API page.

Step 1: Add the Scope Setting​

Add the scope to .env.local, next to the sign-in settings:

.env.local
NEXT_PUBLIC_ENTRA_CLIENT_ID=33333333-3333-3333-3333-333333333333
NEXT_PUBLIC_ENTRA_TENANT_ID=11111111-1111-1111-1111-111111111111
NEXT_PUBLIC_API_SCOPE=api://22222222-2222-2222-2222-222222222222/access_as_user

Like the IDs, the scope isn't a secret: it's in every token request the browser sends. Use your own API's scope. In app/account.tsx, read it once at the top of the file:

app/account.tsx (the scope)
// The permission the access token is for: a scope your API exposes.
const apiScope = process.env.NEXT_PUBLIC_API_SCOPE ?? "";

Step 2: Write getAccessToken​

Inside the component, below useMsal(), add the function that every call to your API will use:

app/account.tsx (getAccessToken)
// Returns an access token for the API: from MSAL's cache while it's valid,
// otherwise a new one, fetched silently. When Microsoft needs the user
// (to sign in again or to consent), sends them there and returns nothing.
async function getAccessToken(): Promise<AuthenticationResult | undefined> {
try {
return await instance.acquireTokenSilent({ scopes: [apiScope], account });
} catch (error) {
if (error instanceof InteractionRequiredAuthError) {
await instance.acquireTokenRedirect({ scopes: [apiScope], account });
return undefined;
}
throw error;
}
}

macOS-style code window titled app/account.tsx showing the getAccessToken function: it returns await instance.acquireTokenSilent with the API scope and the account, and in the catch, when the error is an InteractionRequiredAuthError, awaits instance.acquireTokenRedirect with the same scope and account and returns undefined; any other error is thrown again

LineWhat it does
acquireTokenSilent(…)Returns a cached token while it's valid, or gets a new one with the refresh token, without the person seeing anything
instanceof InteractionRequiredAuthErrorOnly this error means the person has to do something; anything else is a real failure
acquireTokenRedirect(…)Sends the page to Microsoft for that something, then back through your /redirect page
return undefinedThe page is leaving; the caller gets no token this time and tries again when the page comes back
throw errorNetwork problems and other errors reach the caller instead of disappearing

The fallback is a redirect rather than a popup on purpose: MSAL's best practices say that in Safari and on many mobile browsers, prefer acquireTokenRedirect as the interactive fallback from acquireTokenSilent for better reliability.

Step 3: Show What Came Back​

The demo keeps the last result in state and shows three of its fields under a button. The complete file:

app/account.tsx
"use client";

import {
type AuthenticationResult,
InteractionRequiredAuthError,
InteractionStatus,
} from "@azure/msal-browser";
import {
AuthenticatedTemplate,
UnauthenticatedTemplate,
useMsal,
} from "@azure/msal-react";
import { useState } from "react";

// The permission the access token is for: a scope your API exposes.
const apiScope = process.env.NEXT_PUBLIC_API_SCOPE ?? "";

// Shows a Sign in button to visitors, and the account to signed-in users.
export function Account() {
const { instance, accounts, inProgress } = useMsal();
const account = accounts[0];
const [token, setToken] = useState<AuthenticationResult>();

// Returns an access token for the API: from MSAL's cache while it's valid,
// otherwise a new one, fetched silently. When Microsoft needs the user
// (to sign in again or to consent), sends them there and returns nothing.
async function getAccessToken(): Promise<AuthenticationResult | undefined> {
try {
return await instance.acquireTokenSilent({ scopes: [apiScope], account });
} catch (error) {
if (error instanceof InteractionRequiredAuthError) {
await instance.acquireTokenRedirect({ scopes: [apiScope], account });
return undefined;
}
throw error;
}
}

return (
<>
<UnauthenticatedTemplate>
<p>You aren't signed in.</p>
<button
type="button"
disabled={inProgress !== InteractionStatus.None}
onClick={() => void instance.loginRedirect()}
>
Sign in
</button>
</UnauthenticatedTemplate>
<AuthenticatedTemplate>
<p>
Signed in as <strong>{account?.name}</strong> ({account?.username})
</p>
<button
type="button"
onClick={async () => setToken(await getAccessToken())}
>
Get an access token
</button>
{token && (
<dl>
<dt>Scopes</dt>
<dd>{token.scopes.join(" ")}</dd>
<dt>Expires</dt>
<dd>{token.expiresOn?.toLocaleTimeString()}</dd>
<dt>From MSAL's cache</dt>
<dd>{token.fromCache ? "Yes" : "No"}</dd>
</dl>
)}
</AuthenticatedTemplate>
</>
);
}

scopes, expiresOn and fromCache are safe to show. token.accessToken is not: anyone who copies it can call the API as the signed-in person until it expires.

Step 4: Get a Token, Twice​

Sign in, then select Get an access token:

The sign-in demo signed in as Azure User (user@example.com), with a Get an access token button and below it Scopes api://22222222-2222-2222-2222-222222222222/access_as_user, Expires 2:19:41 PM and From MSAL's cache No

From MSAL's cache: No. Signing in had given MSAL tokens for the sign-in only, none for the API. The browser made exactly one request to Microsoft for this click, a POST to login.microsoftonline.com/<tenant ID>/oauth2/v2.0/token: MSAL used the refresh token from the sign-in to get an access token for the API. Microsoft's documentation explains why that works: Refresh tokens are also used to acquire extra access tokens for other resources.

Select it again:

The same demo after a second click: Scopes api://22222222-2222-2222-2222-222222222222/access_as_user, Expires 2:19:41 PM and From MSAL's cache Yes

From MSAL's cache: Yes, with the same expiry, and the browser sent no request to Microsoft at all. Calling getAccessToken() before every API request costs nothing while the token is valid. Microsoft gives access tokens a lifetime of 60 to 90 minutes; this one, fetched a few minutes after 1 PM UTC, expired at 2:19 PM.

Step 5: Send It to Your API​

MSAL's documentation shows the last step: include it in the Authorization header as a bearer token for the request to the resource you obtained the token for:

Calling the API with the token
const result = await getAccessToken();
if (result) {
const response = await fetch("https://your-api.example.com/hello", {
headers: { Authorization: `Bearer ${result.accessToken}` },
});
}

The chat app in the Microsoft Agent Framework series does this with every message it sends to its agent (Part 9: Add Microsoft Entra ID Sign-In to the Next.js Chat App). When the browser talks to your own Next.js server instead, the server passes the header on to the API (How to Forward the Authorization Header from a Next.js Route Handler).

Common Mistakes​

MistakeWhat happensDo this instead
Calling acquireTokenRedirect or a popup firstThe page goes to Microsoft for every tokenacquireTokenSilent first; interactive only on InteractionRequiredAuthError
Treating every error as "sign in again"Network failures send people to Microsoft for nothingCheck instanceof InteractionRequiredAuthError, and throw the rest
Asking for scopes of two APIs in one requestMSAL's documentation: You can only request access tokens for one resource at a timeOne request per API
Keeping the token in your own storageA second copy to protect, and it goes staleAsk MSAL each time; its cache already keeps the token
Showing or logging accessTokenAnyone who sees it can use itShow only scopes, expiresOn, fromCache

Troubleshooting​

SymptomLikely causeFix
acquireTokenSilent throws InteractionRequiredAuthErrorMSAL needs the person: to consent to the scope, or to sign in againLet the redirect run. To skip consent for your own app, pre-authorize it on the API
A redirect to Microsoft about once a dayRefresh tokens for single-page apps last 24 hours, by Microsoft's documentationExpected; the person usually just sees the page reload
The token's audience isn't your APIThe scope doesn't start with your API's Application ID URIUse the full scope from Expose an API
From MSAL's cache stays Yes for an hourMSAL returns the cached token while it's validExpected

FAQ​

Do I need to check the token's expiry myself?​

No. acquireTokenSilent checks it and gets a new token when the cached one is close to expiring. Call it before every request.

Why does the first call go to Microsoft when I'm already signed in?​

Signing in gave MSAL an ID token and a refresh token, but no access token for your API. The first acquireTokenSilent for the API's scope redeems the refresh token for one, silently.

Where does MSAL keep the token?​

In its cache, in the browser's sessionStorage unless you set cacheLocation otherwise. Closing the tab clears it.

Conclusion​

To call an API from a React app, get the token with acquireTokenSilent({ scopes: [<API scope>], account }) before every request, fall back to acquireTokenRedirect only on InteractionRequiredAuthError, and send result.accessToken in an Authorization: Bearer header. The live run showed the first call redeeming the refresh token with one request to Microsoft, and the second answered from MSAL's cache with none.

Additional Resources​