Search code examples
reactjsazureasp.net-web-apioauth-2.0azure-active-directory

Getting access token from Azure AD from React frontend


I have a React SPA and ASP.NET web API, both registered applications on Azure.

I have authentication setup so the user logs in and authenticates through the tenant for the front-end application. But now I need to get a bearer token for the API application in the front-end to pass along with the API calls.

I figured the workflow would:

Call https://login.microsoftonline.com/TEANTID/oauth2/v2.0/authorize -> get authorization code -> Call https://login.microsoftonline.com/TENANTID/oauth2/v2.0/token with previous auth code, which will return a bearer token to use in the API call, but both the top requests will always return

"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."

My understanding is I cannot change that, so what must I be doing wrong here? I can see Swagger calling those endpoints just fine as well as Postman but I cannot replicate.

I followed a lot of the examples and guides but they only seem to be for getting an access token for the front-end application. I have that, but now I need to also authenticate for the API afterwards.

This is my msalConfig being used to authenicate into the front-end

export const msalConfig = {
auth: {
    clientId: "FRONT-END-APP-ID",
    authority: "https://login.microsoftonline.com/TENANTID",
    redirectUri: "http://localhost:3000"
},
cache: {
    cacheLocation: "sessionStorage", // This configures where your cache will be stored
    storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
}

Index.tsx

   const msalInstance = new PublicClientApplication(msalConfig);

const root = ReactDOM.createRoot(
    document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
    <MsalProvider instance={msalInstance}>
      <App />
    </MsalProvider>
  </React.StrictMode>
);

Solution

  • I tried to reproduce the same in my environment and got the results like below:

    I created two Azure AD Applications and exposed an API in ASP.NET web API App:

    enter image description here

    I agree with Gaurav Mantri, In the React SPA (Frontend) Application added the API permission like below:

    enter image description here

    I generated auth-code by using below endpoint:

    https://login.microsoftonline.com/TenantId/oauth2/v2.0/authorize?
    client_id=ClientID
    &response_type=code
    &redirect_uri=RedirectUri
    &response_mode=query
    &scope=api://ClientID/.default
    &code_challenge=XXXXX
    &code_challenge_method=S256
    

    enter image description here

    I generated access token by using below parameters:

    enter image description here

    enter image description here

    Modify the msalConfig file of your React Frontend like below:

    auth: { 
    authority: "https://login.microsoftonline.com/TenantID",
    clientId: "ClientID",
    postLogoutRedirectUri: RedirectURI
    redirectUri: RedirectURI
    validateAuthority: true,
    navigateToLoginRequestUrl: true,
    },
    cache:
    { cacheLocation: 'sessionStorage',
    storeAuthStateInCookie: true,
    },
    },
    {
    scopes: ['api://clientid/.default']
    },
    LoginType.Redirect
    

    If still the issue persists, add the CORS policy in your React Application by setting it by allowing all the origin. cors.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());

    Reference:

    React.JS + MSAL with ASP.NET Core to use Azure AD by Mark Deanil Vicente