2

Today I was configuring authorization provider for Oauth middleware and trying to insert some guid value into Thread.CurrentPrincipal.Identity.Claims. But when I tried to call Thread.CurrentPrincipal's FindFirst I've got nothing.

Here is the example what I was trying to do:

public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    var claimsIdentity = Thread.CurrentPrincipal.Identity as ClaimsIdentity;

    if (claimsIdentity != null)
       claimsIdentity.AddClaim(new Claim("TestClaim", Guid.NewGuid().ToString()));

    var claimValue = ((ClaimsPrincipal)Thread.CurrentPrincipal)
        .FindFirst(x => x.Type == "TestClaim"); //claimValue == null!
}

Checking inner properties, found that Thread.CurrentPrincipal.Identity still contains claim I've set before, but Thread.CurrentPrincipal.Identities[0] - doesn't. So there are two different identity instances with their own set of claims.

I tried to do the same steps inside Web Api controller's action and there Identity was referencing to Identities[0] which means that there is the same instance.

What is happening to OWIN middleware's Currentprincipal so it's Identity and Identities[0] refer to different instances? Can anyone explain me this, please?

Thank you!

Refraction
  • 183
  • 1
  • 12

1 Answers1

0

I met the same issue. I don't know why the Identity property and the first identity of the Identities property are different instances...
But it seems that all methods relative to claims in the ClaimsPrincipal class (Claims, FindFirst...) are based on the Identities property, so updating the Identity property has no effect.
I prefer to keep the two identities consistent, so I use the following workaround to solve the problem :

principal = (ClaimsPrincipal)Thread.CurrentPrincipal
identity = (ClaimsIdentity)user.Identity;
identity1 = user.Identities.First();
identity.AddClaim(claim);
identity1.AddClaim(claim);
gentiane
  • 6,715
  • 3
  • 23
  • 34