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

jubing long 121 Reputation points
2022-02-10T13:05:17.287+00:00

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.
axios.interceptors.request.use(
config => {
const token = getAccessTokenInSync();
config.headers.Authorization = Bearer ${token};
}
);

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

Best wishes~

Azure Active Directory
Azure Active Directory
An Azure enterprise identity service that provides single sign-on and multi-factor authentication.
13,443 questions
No comments
{count} votes

Accepted answer
  1. Shweta Mathur 12,671 Reputation points Microsoft Employee
    2022-02-14T12:19:43.477+00:00

    Hi @jubing long ,

    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.

    Thanks,
    Shweta

    ---------------------------------------------------

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


0 additional answers

Sort by: Most helpful