简体   繁体   中英

Using ClaimsIdentity to retrieve user profile via AAD graph

I am building user authentication based on Azure Active Directory using OpenId Connect. I can successfully log into my website by using my account in AAD. After I'm logged in, I would like to retrieve my account information via the AAD graph API.

I can get the user ID via the ClaimsIdentity:

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

And I can get user information via the graph 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. 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:

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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