【问题标题】:Get list of Microsoft Azure AD group names using MSAL library in Angular 8使用 Angular 8 中的 MSAL 库获取 Microsoft Azure AD 组名称列表
【发布时间】:2021-04-18 01:01:14
【问题描述】:

我正在开发一个 Angular 8 应用程序,它试图检索登录用户可用的所有 Microsoft AD 组的列表。 以前,我正在使用 MSAL 库对用户进行身份验证,并成功获得以下值:

  • 访问令牌
  • idToken
  • 家庭标识符
  • 过期时间

我的 MSAL 配置如下:

export function MSALAngularConfigFactory(): MsalAngularConfiguration {
  var isIE = window.navigator.userAgent.indexOf("MSIE ") > -1 ||
    window.navigator.userAgent.indexOf("Trident/") > -1;
  return {
    popUp: !isIE,
    consentScopes: [
      'user.read',
      'openid',
      'profile',
      'group.Read.All'
    ],
    unprotectedResources: ['https://www.microsoft.com/en-us/'],
    protectedResourceMap: [
      ['https://graph.microsoft.com/v1.0/me', ['user.read']],
      ['https://graph.microsoft.com/v1.0/groups', ['group.read.all']]
    ]
  };
}
export function MSALConfigFactory(): Configuration {
  var isIE = window.navigator.userAgent.indexOf("MSIE ") > -1 ||
    window.navigator.userAgent.indexOf("Trident/") > -1;
  return {
    auth: {
      clientId: environment.clientId,
      authority: environment.authority,
      validateAuthority: true,
      redirectUri: environment.redirectUrl,
      postLogoutRedirectUri: environment.redirectUrl,
      navigateToLoginRequestUrl: true,
    },
    cache: {
      cacheLocation: 'localStorage',
      storeAuthStateInCookie: isIE,
    }
  };
}

当我调用 MSAL 的 getAccount().idTokenClaims['groups'] 方法时,它返回给我的组数组只有一些标识符值,这不是我的要求。我需要一组 AD 组名称。

我也实现了 MicrosoftGraph 库以使用以下 API 获取组:

fetch('https://graph.microsoft.com/v1.0/groups', {
     headers: {
         'Authorization': 'Bearer ' + {access_token},
         'Content-Type': 'application/json',
     }
 }).then(res => { console.log(res); });

上面的代码总是导致错误说明: 401(未经授权)

我尝试了 Microsoft Graph 的多种解决方案,包括:

const msalConfig = {
      auth: {
        clientId: clientId, // Client Id of the registered application
        redirectUri: "https://localhost:4200",
      }
 };
 const graphScopes = ["user.read", "group.read.all"]; // An array of graph scopes
 const msalApplication = new UserAgentApplication(msalConfig);
 const options = new MSALAuthenticationProviderOptions(graphScopes);
 const authProvider = new ImplicitMSALAuthenticationProvider(msalApplication, options);

 this.subscription1 = broadcast.subscribe("msal:loginSuccess",
      (result) => {
        //The result has accessToken as null.
        fetch('https://graph.microsoft.com/v1.0/groups', {
          headers: {
            'Authorization': 'Bearer ' + {accessToken},
            'Content-Type': 'application/json',
          }
        }).then(response => { console.log(response);});

上面的代码 sn-p 也返回一个错误,说明:

CompactToken 解析失败,错误代码:80049217

我已经尝试了更多解决方案,但对我没有任何帮助。我从昨天开始就卡在里面了。

谁能帮我找出最好的解决方案。任何帮助将不胜感激。

提前致谢。

【问题讨论】:

  • 看起来主要问题是访问令牌无效。你怎么得到它?在jwt.io解码就可以看到详细信息了。
  • 嗨@AllenWu。感谢您的观察。这实际上是我的 accessToken 的问题。我使用的方法没有返回任何 accessToken。我使用的另一种方法是处理过期的令牌。 jwt.io 是一种非常简单而优雅的方式来检查您的令牌状态。

标签: azure-active-directory microsoft-graph-api angular8 msal usergroups


【解决方案1】:

不太确定您的应用程序的上下文。我的代码演示基于this official Angular MSAL demo

src/app/app.module.ts正确配置此应用后,转到src/profile/profile.component.ts添加以下函数以获取所有组名:

  getAccessTokenAndCallGraphAPI(){

    this.authService.acquireTokenSilent({
      scopes: ['group.Read.All']
    }).then(result=>{
      const httpOptions = {
        headers: new HttpHeaders({
          'Content-Type':  'application/json',
          Authorization: 'Bearer '+result.accessToken
        })}

      this.http.get("https://graph.microsoft.com/v1.0/groups?$select=id,displayName",httpOptions).toPromise().then(result=>{console.log(result)});
    })
  }

在页面初始化时调用这个函数:

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

结果: 访问“配置文件”页面将在控制台中打印所有组的 ID 和名称。

在调用此 API 之前,请确保您已授予应用程序以下权限:

【讨论】:

  • 非常感谢您的回复。它就像一个魅力。我试图创建一个 userApplicationAgent 的实例,AuthenticationProvider 作为参数传递给 acquireTokenSilent 查看一些文档,并调用 fetch 方法来使用图形获取数据组。但这导致了空的accessToken。但是这段代码完美无缺。我还有另一个类似的问题。一会儿我也会想出这个。我相信我也会得到一个详细而正确的解释。再次感谢。
猜你喜欢
  • 2020-02-19
  • 1970-01-01
  • 1970-01-01
  • 2021-03-19
  • 2021-07-23
  • 2020-09-13
  • 1970-01-01
  • 2019-06-19
  • 1970-01-01
相关资源
最近更新 更多