microsoft login api: how to get code to exchange refresh_token

40 Views Asked by At

There are two steps in getting a refresh_token. The first step is to get a code from https://login.microsoftonline.com/common/oauth2/v2.0/authorize endpoint. The second step is to exchange the code you get from step 1 to get the refresh_token from the https://login.microsoftonline.com/common/oauth2/v2.0/token endpoint.

If I set the type of redirect_uri to web on entra.microsoft.com, then the first step works, but the second step would return an error saying that: AADSTS90023: Cross-origin token redemption is permitted only for the 'Single-Page Application'.

If I set the type of redirect_uri to Single-page application on entra.microsoft.com, then the first step errors with error_description: Proof Key for Code Exchange is required for cross-origin authorization code redemption.

Any ideas to get the refresh_token from microsoft login?

1

There are 1 best solutions below

0
Steve Lewis On

After days of research, I finally found a package as a potential solution: npm i @azure/msal-browser

MSAL.js abstracts away all refresh token complexity and thus refresh tokens are not exposed by MSAL APIs by design. When you need an access token please call the acquireTokenSilent API which will return to you a valid token from the cache or internally use the refresh token to acquire a new access token.

Here is a code snippet:

return pca.acquireTokenSilent(silentRequest).catch(e => {
  if (e instanceof InteractionRequiredAuthError) {
    return pca.acquireTokenInteractive(loginRequest)
  }
});