首页 > 解决方案 > 我想在 Angular 7+ http 调用中从 Microsoft graph 调用 Token API

问题描述

从角度应用程序我想调用https://login.microsoftonline.com/##tenant##/oauth2/v2.0/token api 从 http 调用获取访问令牌并使用我想调用的令牌https:// graph.microsoft.com/v1.0/users/##UserId##​​​​​​​​​​​​​​​​​​​​​​​​​​/getMemberGroups API,而不使用任何角度的npm包。

我尝试使用 http 服务,但出现以下错误

从源“https://xxx.co”访问“https://login.microsoftonline.com/xxxx/oauth2/v2.0/token”的 XMLHttpRequest 已被 CORS 策略阻止:否“访问控制允许” -Origin' 标头存在于请求的资源上。

有没有其他方法可以调用 Graph API 以获取令牌和用户获取登录用户组?

标签: angularazure-active-directorymicrosoft-graph-apiadal

解决方案


https://login.microsoftonline.com/<tenant>/oauth2/v2.0/token 由于 CORS,不允许直接从信号页面应用程序调用。您应该将 MSAL 用于 Angular 来执行此操作。我的代码基于这个 Angular 官方演示

请转到src/app/app.module.ts配置您的 Azure 广告:

在此处输入图像描述

并首先运行这个演示。

成功运行此演示后,转到profile.component.ts,添加以下代码:

  getAccessTokenAndCallGraphAPI(){

    this.authService.acquireTokenPopup({
      scopes: ['GroupMember.Read.All']
    }).then(result=>{
      console.log("access token: "+ result.accessToken)

      const httpOptions = {
        headers: new HttpHeaders({
          'Content-Type':  'application/json',
          Authorization: 'Bearer '+result.accessToken
        })}

      const reqBody = {
        "securityEnabledOnly": true
      }
      this.http.post("https://graph.microsoft.com/v1.0/users/<user you want to query>/getMemberGroups",reqBody,httpOptions).toPromise().then(result=>{console.log(result)});
    })
  }

初始化页面时调用该函数:

ngOnInit() {
    this.getProfile();
    this.getAccessTokenAndCallGraphAPI();
  }

结果:

在此处输入图像描述

如果您还有其他问题,请告诉我。


推荐阅读