Reputation: 150
I need to store a unique identifier for a user in an SQL database. My application uses OpenID Connect via OWIN to authenticate users against Azure AD and is based on the MVC 5 Framework. I can access the ObjectId of the user via the http://schemas.microsoft.com/identity/claims/objectidentifier claim. The only way I know how to obtain the claims is with a delegate added to the "Notifications" property of "OpenIdConnectAuthenticationOptions". As this is part of the application startup the delegate has no way of passing this information on to a session.
I have seen answers to questions with similar goals that recommend using the Graph API to match the User.Identity.Name with the ObjectId. I would rather avoid doing this as my application is resource hungry enough as it is.
Here is what I have so far. I just need to get the claim into a Session, or access the claims from a Session. (This doesn't always work, for example if the user is already logged in, but it's the best I have so far)
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthorizationCodeReceived = (context) =>
{
IEnumerable<Claim> claims = context.AuthenticationTicket.Identity.Claims;
Claim objectId = claims.First(claim => claim.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier");
// ???
return Task.FromResult(0);
}
},
Upvotes: 0
Views: 877
Reputation: 150
I think I've answered my own question. This works nicely.
ClaimsIdentity identity = User.Identity as ClaimsIdentity;
Guid objectId = new Guid(identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value);
Guid tenantId = new Guid(identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value);
Upvotes: 1