如何在Angular中通过ng2-adal从Azure AD获取用户组名称
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:
- Go to the Azure Portal, navigate to your App Registration.
- Select Token configuration from the left menu.
- Click Add optional claim, choose ID token as the token type.
- Find and select the
groupsclaim, then check the box labeled "Return group names as claim values". - 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.AllorGroup.ReadBasic.Alldelegated 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
acquireTokenwill automatically refresh expired tokens for you).
内容的提问来源于stack exchange,提问作者JibinNajeeb

