0

I built an angular application which uses MSAL to generate access token as a part of login process. My application is also required to access the API (OpenAPI) hosted in API gateway in Azure.My application has to be ultimately hosted in Azure only. However when I tried generating token using clientid, grant_type (client_credentials),client_secret, scope and resource in body (x-www-form-urlencoded) and https://login.microsoftonline.com/</oauth2/token (or v2 url) in Postman, I'm able to generate the token and use it in my angular code and access the API whereas when I tried to generate the token in the angular code itself, it is not generating the token. It results in CORS error. Any help is appreciated. Below is sample code for reference. I created app registration for this application in Azure and tried to use the login access token also, but it is not allowing. let headers = new HttpHeaders({

  'Content-Type': 'application/x-www-form-urlencoded',

  'Access-Control-Allow-Origin' : '*'

});

let body = new URLSearchParams();



body.set('grant_type', "client_credentials");

body.set('client_id', "cliend id here");

body.set('client_secret', "secret here");

body.set('resource', 'resource here');



return this.http.post<any>(this.url, body.toString(), {

  headers: headers

}).pipe(

 

  map(jwt => {

    console.log('access token generated successfully', jwt.access_token);

    if (jwt && jwt.access_token) {

      localStorage.setItem('HAPIToken', JSON.stringify(jwt))

    }

  }),

  catchError((this.handleError))

).subscribe();
  • Does this answer your question? [How to fix CORS issue http request in Angular 5](https://stackoverflow.com/questions/48456448/how-to-fix-cors-issue-http-request-in-angular-5) – Ecstasy Mar 25 '22 at 04:49
  • Thank you so much for your answer. I'm bit confused about the answers presented in the referenced posts. what I really need is that can the angular code generate token by providing the parameters such as client id, client secret,grant type and resource in body (x-www-form-encoded) and posting it to https://login.microsoftonline.com/<>/oauth2/token?. Secondly CORS error is because of the fact that from my localhost, I'm accessing microsoft AD tenant url which is the cross site. if the same application is deployed in Azure, will this CORS error go and token will be generated. – user3667809 Mar 25 '22 at 16:50
  • https://stackoverflow.com/questions/68885579/get-access-token-azure-ad-using-client-secret-key-client-credential-flow-angul?rq=1 - This post exactly explains my scenario. But it looks like generating token in angular is not a good idea except in case of login scenario and it shouldn't be adhered to at any cost. – user3667809 Mar 25 '22 at 17:32

0 Answers0