简体   繁体   English

使用ClaimsIdentity通过AAD图检索用户个人资料

[英]Using ClaimsIdentity to retrieve user profile via AAD graph

I am building user authentication based on Azure Active Directory using OpenId Connect. 我正在使用OpenId Connect基于Azure Active Directory构建用户身份验证。 I can successfully log into my website by using my account in AAD. 我可以使用AAD中的帐户成功登录我的网站。 After I'm logged in, I would like to retrieve my account information via the AAD graph API. 登录后,我想通过AAD图形API检索我的帐户信息。

I can get the user ID via the ClaimsIdentity: 我可以通过ClaimsIdentity获取用户ID:

ClaimsIdentity identity = this.User.Identity as ClaimsIdentity;
string userID = identity.GetUserId();

And I can get user information via the graph API: 我可以通过图形API获取用户信息:

public IUser GetProfileById(string userID)
{
    ActiveDirectoryClient client = GetAadClient();
    var user = client.Users.Where(x => x.ObjectId == userID).ExecuteSingleAsync().Result;
    return user;
}

However, the user ID that is stored on the ClaimsPrincipal does not seem to be the Object ID in AAD, so I'll need to find some other way to retrieve the user information. 但是,存储在ClaimsPrincipal上的用户ID似乎不是AAD中的对象ID,因此,我需要找到其他方法来检索用户信息。 Another option might be to find the user based on the email address, but I can't find out how to do that either. 另一个选择可能是根据电子邮件地址查找用户,但是我也找不到如何执行此操作。 Any help or suggestions will be appreciated. 任何帮助或建议,将不胜感激。

Thanks to @juunas I found out the type: 感谢@juunas,我找到了类型:

ClaimsIdentity identity = this.User.Identity as ClaimsIdentity;
string objectID = identity.Claims.FirstOrDefault(x => x.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier")?.Value;

Then the object ID can be used to obtain the user information via the AAD graph API. 然后,可以使用对象ID通过AAD图形API获得用户信息。

Here's a quick answer for anyone else still looking. 这是仍在寻找其他人的快速解答。

 public void GetUserFromAD(GraphServiceClient gsc)
    {
        try
        {
            ClaimsIdentity identity = ClaimsPrincipal.Current.Identity as ClaimsIdentity;
            string objectID = identity.Claims.FirstOrDefault(x => x.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier")?.Value;
            var user = gsc.Users[objectID].Request().GetAsync().Result;

        }
        catch(Exception ex)
        {
            // do something.
        }
    }

Note you can use direct lookup using Users[objectid] rather than enumerating through the result list. 请注意,您可以使用Users [objectid]直接查找,而不是通过结果列表进行枚举。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM