使用客户端凭据从角度应用程序调用 Azure API 网关中托管的企业 API(使用 microsoft 令牌 url 生成令牌

发布于 2025-01-17 02:55:00 字数 1025 浏览 1 评论 0原文

我构建了一个角度应用程序,它使用 MSAL 生成访问令牌作为登录过程的一部分。我的应用程序还需要访问 Azure API 网关中托管的 API (OpenAPI)。我的应用程序最终只能托管在 Azure 中。但是,当我尝试使用 clientid、grant_type (client_credentials)、client_secret、body (x-www-form-urlencoded) 中的范围和资源以及 https://login.microsoftonline.com/

  '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();

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();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文