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

如何通过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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:44:00