0

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);
  }
},
James S.
  • 140
  • 2
  • 12

1 Answers1

1

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);
James S.
  • 140
  • 2
  • 12
  • 1
    It's got me on a timer I'll be able to accept it tomorrow. Thanks for reminding me. – James S. Dec 18 '18 at 22:53
  • Long time ago, I know, but how were you referencing "User" from within the application Startup? Isn't that a property of a Controller? Or were you pulling context.OwinContext.Authentication.User? – ChristopherBass Sep 23 '20 at 14:14