如何通过ClaimsIdentity结合AAD Graph获取用户配置文件?
解决AAD登录后通过Graph API获取用户信息的问题
嘿,我懂你现在遇到的麻烦——登录后用GetUserId()拿到的ID和AAD里的Object ID对不上,导致没法直接用Graph API查用户信息对吧?别慌,这里有两个实用的解决方案:
方法一:直接从Claims中提取AAD Object ID
其实AAD已经把用户的Object ID放在登录后的Claims集合里了,只是GetUserId()默认取的不是这个字段。你可以直接定位到对应的Claim类型:
// 方式1:通过ClaimsIdentity查找 ClaimsIdentity identity = this.User.Identity as ClaimsIdentity; string objectId = identity?.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier")?.Value; // 方式2:更简洁的写法 string objectId = this.User.FindFirstValue("http://schemas.microsoft.com/identity/claims/objectidentifier");
拿到Object ID之后,你原来的查询方法就能正常工作了,记得把同步的.Result改成await避免死锁:
public async Task<IUser> GetProfileById(string userID) { ActiveDirectoryClient client = GetAadClient(); var user = await client.Users.Where(x => x.ObjectId == userID).ExecuteSingleAsync(); return user; }
方法二:通过邮箱/UPN查询用户
如果因为某些场景没法获取Object ID,用邮箱或者用户主体名称(UPN)查询也是靠谱的。先从Claims里拿到用户的邮箱:
public async Task<IUser> GetProfileByEmail() { // 先尝试获取邮箱Claim string userEmail = this.User.FindFirstValue("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"); if (string.IsNullOrEmpty(userEmail)) { // 有些用户可能没设置Mail字段,试试用UPN(通常也是邮箱格式) userEmail = this.User.FindFirstValue("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"); if (string.IsNullOrEmpty(userEmail)) { // 处理没有邮箱/UPN的异常情况 return null; } } ActiveDirectoryClient client = GetAadClient(); // 同时匹配Mail和UserPrincipalName,覆盖更多用户场景 var user = await client.Users .Where(x => x.Mail == userEmail || x.UserPrincipalName == userEmail) .ExecuteSingleAsync(); return user; }
额外提醒
- 确保你的AAD应用注册时已经添加了Graph API的权限(比如
User.ReadBasic.All或User.Read),如果是租户级应用还需要完成管理员同意。 - 尽量用
async/await异步调用,别用同步阻塞的.Result,避免Web应用出现死锁问题。
内容的提问来源于stack exchange,提问作者Bart van der Drift
相关产品推荐
相关产品推荐

