how to get accessToken by msal-browser.js in sync

(Neusoft)龍 挙兵(Ryuu.Kixyoheyi) 121 Reputation points

My SPA application Using msal-browser.js to login to Azure.
When SPA application send request to back api, I will use the accessToken.
So I Call PublicClientApplication.prototype.acquireTokenSilent to get accessToken.
But the acquireTokenSilent method is async.
I have to use myMSALObj.acquireTokenSilent(request).then(response => {
send api with accessToken
I want to set the accessToken to header by common. so I want to get the accessToken in sync.
config => {
const token = getAccessTokenInSync();
config.headers.Authorization = Bearer ${token};

Is there anyway to get the accessToken in sync by msal-browser.js.

Best wishes~

Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
20,531 questions
0 comments No comments
{count} votes

Accepted answer
  1. Shweta Mathur 29,531 Reputation points Microsoft Employee

    Hi @Anonymous ,

    Thanks for reaching out.

    From your query I understand that you are looking for built in MSAL method to get access token synchronously.

    MSAL doesn’t seem to have synchronous method to acquire token. MSAL provide built in methods to AquireToken asynchronously.

    In other way, y ou can try to use Async/Await in a method to make asynchronous code behave in a synchronous way. The async method is executed just like any other method. That is, it runs synchronously until it hits an “await” (or throws an exception).

    Or you could easily enhance your code by calling MSAL acquireTokenSilent and making it synchronous with locks to block the current thread until the response is received.

    Hope this will help to address your scenario.



    Please remember to "Accept Answer" if answer helped you.

0 additional answers

Sort by: Most helpful