Home > Software engineering >  Getting CORS error while fetching access token based on client cred on Microsoft Azure AD authentica
Getting CORS error while fetching access token based on client cred on Microsoft Azure AD authentica

Time:01-21

I am trying to get an access token based on client credentials like (client id, client secret, tenant id, and scope).

It's working fine when I was testing it through PostMan but when I try to fetch through my angular app like below, it throws CORS error.

Tried directly as well as with @azure/identity package too:

let clientSecretCredential = new ClientSecretCredential(
  '*********',
  '*********',
  '*********'
)
clientSecretCredential.getToken('api://*******/.default',{}).then((accessToken: AccessToken) => {
  console.log("Access Token:",accessToken);
}).catch((reason: any) => {
  console.log("Error while generating Access Token:",reason);
});

I tried the below things to solve the CORS issue.

Azure suggestion:

Redirect URIs for single-page apps (SPAs) Redirect URIs for SPAs that use the auth code flow require special configuration.

Add a redirect URI that supports auth code flow with PKCE and cross-origin resource sharing (CORS):

URI: MSAL.js 2.0 with auth code flow. Update a redirect URI: Set the redirect URI's type to spa by using the application manifest editor in the Azure portal. The spa redirect type is backward-compatible with the implicit flow. Apps currently using the implicit flow to get tokens can move to the spa redirect URI type without issues and continue using the implicit flow.

If you attempt to use the authorization code flow without setting up CORS for your redirect URI, you will see this error in the console: Follow the steps in Redirect

Added redirect URIs:

http://localhost:4200

But still throws a CORS issue.

so here I want to know if it is right to generate an access code from SPA through client credentials.

On azure alos I can't see any sample or docs which help me to implement access code base authentication on my API.

Can anyone guide me on this if it's not the right way?

Note: Its user less authentication as there is no user in AD system.

CodePudding user response:

You cannot use ClientSecretCredential in a front-end application. Your client secret is a password and will be leaked to anyone visiting your app.

You need to use @azure/msal-angular or @azure/msal-browser to acquire tokens. These will require the user to login and then you can call APIs on their behalf.

  • Related