You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular中通过ng2-adal从Azure AD获取用户组名称

Getting Group Names from Azure AD Token using ng2-adal

Great question! Let's walk through how to retrieve group names using ng2-adal, since that's your preferred tool for Azure AD integration.

Option 1: Get Group Names Directly from the Token (Preferred)

By default, Azure AD's ID token only includes group IDs in the groups claim. But you can configure your Azure AD app registration to include group names in the token itself—this is the simplest approach because you won't need extra API calls.

Steps to Configure Optional Claims:

  1. Go to the Azure Portal, navigate to your App Registration.
  2. Select Token configuration from the left menu.
  3. Click Add optional claim, choose ID token as the token type.
  4. Find and select the groups claim, then check the box labeled "Return group names as claim values".
  5. Save your changes.

Retrieve Group Names via ng2-adal:

Once configured, you can fetch the token from ng2-adal and extract the group names directly:

import { AdalService } from 'ng2-adal/core';

constructor(private adalService: AdalService) {}

getGroupNames() {
  // Get cached ID token
  const idToken = this.adalService.getCachedToken(this.adalService.config.clientId);
  
  // Use ng2-adal's built-in token info parser
  const tokenInfo = this.adalService.adal.getTokenInfo(idToken);
  
  // Now tokenInfo.groups will contain group names (instead of IDs)
  console.log('Group Names:', tokenInfo.groups);
}

You can also check the cached user info directly:

const userInfo = this.adalService.userInfo;
// If the token has group names, they might be available in userInfo.profile.groups
console.log('User Profile Groups:', userInfo.profile.groups);

Option 2: Fetch Group Names via Microsoft Graph API (If Optional Claims Aren't Feasible)

If you can't modify the Azure AD app configuration, you'll need to use the Microsoft Graph API to look up group names using the IDs from your token. ng2-adal can help you get the access token for Graph API.

Prerequisites:

  • Ensure your Azure AD app registration has the Group.Read.All or Group.ReadBasic.All delegated permission (grant admin consent if required).

Code to Fetch Group Names:

import { AdalService } from 'ng2-adal/core';
import { HttpClient } from '@angular/common/http';

constructor(private adalService: AdalService, private http: HttpClient) {}

fetchGroupNames(groupIds: string[]) {
  // Get access token for Microsoft Graph
  this.adalService.acquireToken('https://graph.microsoft.com')
    .subscribe(accessToken => {
      // Batch fetch groups using their IDs
      const filterQuery = groupIds.map(id => `id eq '${id}'`).join(' or ');
      const graphUrl = `https://graph.microsoft.com/v1.0/groups?$filter=${filterQuery}&$select=id,displayName`;
      
      this.http.get(graphUrl, {
        headers: { Authorization: `Bearer ${accessToken}` }
      }).subscribe((response: any) => {
        // Map the response to get id-to-name pairs
        const groupNameMap = response.value.reduce((map: any, group: any) => {
          map[group.id] = group.displayName;
          return map;
        }, {});
        
        console.log('Group Name Mapping:', groupNameMap);
      });
    });
}

Call this function with your group IDs array:

const groupIds = ["4ba2649e-20d2-40f4-a406-2ed897686403","43e19f05-c077-4716-b001-0ffb0d75fff8"];
this.fetchGroupNames(groupIds);

Key Notes:

  • Option 1 is better because it avoids extra network calls and leverages ng2-adal's existing token handling.
  • If you go with Option 2, make sure to handle token expiration (ng2-adal's acquireToken will automatically refresh expired tokens for you).

内容的提问来源于stack exchange,提问作者JibinNajeeb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:15:40