使用 Angular 8 中的 MSAL 库获取 Microsoft Azure AD 组名称列表

问题描述

我正在开发一个 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},}
        }).then(response => { console.log(response);});

上面的代码片段也返回一个错误,说明:

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

我尝试了更多解决方案,但没有任何效果。我从昨天开始就陷进去了。

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

提前致谢。

解决方法

不太确定您的应用程序的上下文。我的代码演示基于 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 和名称。 enter image description here enter image description here

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...