如何通过用户ID(对象ID)从Azure Active Directory获取用户名
解决方案
1. 利用当前用户的委托权限(User.ReadBasic.All)
如果你的应用能申请到User.ReadBasic.All委托权限(这个权限比User.Read.All宽松,多数租户允许普通应用申请),可让前端通过MSAL获取用户访问令牌,调用Microsoft Graph的/users/{userId}端点,该权限能获取用户基本信息(包含displayName、userPrincipalName等核心字段,足够满足用户名获取需求)。
前端(Vue.js + MSAL)示例:
// 初始化MSAL实例后,获取访问令牌 const tokenRequest = { scopes: ["https://graph.microsoft.com/User.ReadBasic.All"] }; const response = await msalInstance.acquireTokenSilent(tokenRequest); const accessToken = response.accessToken; // 调用Graph API获取用户信息 const userId = "目标用户的ID"; const userInfo = await fetch(`https://graph.microsoft.com/v1.0/users/${userId}`, { headers: { Authorization: `Bearer ${accessToken}` } }).then(res => res.json()); // 提取用户名 const userName = userInfo.displayName || userInfo.userPrincipalName;
2. 借助Azure AD扩展属性或自定义存储
若无法申请任何Graph权限,可采取以下方式:
- 在用户创建/更新时,通过Azure AD的Provisioning功能,或用户首次登录时,将用户ID与用户名同步到应用自有数据库
- 后续直接从数据库通过用户ID查询用户名,无需调用Microsoft Graph
后端(.NET Core)示例:
// 假设存在操作数据库的UserRepository类 public async Task<string> GetUserNameById(string userId) { var user = await _userRepository.GetAsync(u => u.AzureAdUserId == userId); return user?.UserName; }
3. 申请有限范围的应用权限(备选方案)
若租户管理员允许,可申请User.Read.All应用权限并限制访问范围到特定安全组,这样后端仅能读取组内用户信息,降低权限风险。
.NET Core后端调用示例:
// 用客户端凭据模式获取应用令牌 var scopes = new[] { "https://graph.microsoft.com/.default" }; var clientSecretCredential = new ClientSecretCredential( tenantId, clientId, clientSecret); var graphClient = new GraphServiceClient(clientSecretCredential, scopes); var user = await graphClient.Users[userId] .Request() .Select(u => new { u.DisplayName, u.UserPrincipalName }) .GetAsync(); var userName = user.DisplayName ?? user.UserPrincipalName;
4. 用户手动提供目标用户信息(临时方案)
若以上方案均不可行,可在前端让用户输入目标用户的用户名或邮箱,再通过Graph的/users/{userPrincipalName}端点查询(同样使用User.ReadBasic.All权限),但该方式依赖用户输入,无法自动获取。
内容的提问来源于stack exchange,提问作者Lev Kostychenko
相关产品推荐
相关产品推荐

