【问题标题】:I want to call Token API from Microsoft graph in angular 7+ http call我想在 Angular 7+ http 调用中从 Microsoft graph 调用 Token API
【发布时间】:2021-05-09 05:03:44
【问题描述】:

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

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

CORS 策略已阻止从源“https://xxx.co”访问“https://login.microsoftonline.com/xxxx/oauth2/v2.0/token”处的 XMLHttpRequest:无“访问权限-请求的资源上存在 Control-Allow-Origin' 标头。

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

【问题讨论】:

标签: angular azure-active-directory microsoft-graph-api adal


【解决方案1】:

不允许拨打https://login.microsoftonline.com/<tenant>/oauth2/v2.0/token 由于 CORS,直接来自信号页面应用程序。您应该将 MSAL 用于 Angular 来执行此操作。我的代码基于this angular official demo

请前往src/app/app.module.ts 配置您的 Azure 广告:

首先运行这个演示。

成功运行此demo后,前往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();
  }

结果:

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

【讨论】:

  • 未提供“interceptorConfig”的参数。上述代码在app.module中出现此错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-09
  • 2021-11-17
  • 2017-01-18
相关资源
最近更新 更多