Thread.CurrentPrincipal is authenticated, but ClaimsPrincipal.Current is not

I use claims-based authorization in my WebApi project and have a method in which I check if the current identity is verified. When I use ClaimsPrincipal.Current , the current authentication is not authenticated, but when I use Thread.CurrentPrincipal , it is.

 ClaimsPrincipal.Current.Identity.IsAuthenticated; //False Thread.CurrentPrincipal.Identity.IsAuthenticated; //True 

This seems strange, especially since MSDN says ClaimsPrincipal.Current simply returns Thread.CurrentPrincipal:

Notes

By default, Thread.CurrentPrincipal is returned. You can change this by setting the ClaimsPrincipalSelector property to specify the delegate to invoke the current principal.

Can someone explain to me why ClaimsPrincipal not authenticated, while both theoretically contain the same identity?

+4
source share
1 answer

In short, the documentation is incorrect to say that it returns Thread.CurrentPrincipal by default.

What it actually returns is ClaimsPrincipal wrapping Thread.CurrentPrincipal (if it is not, there is already ClaimsPrincipal ) using this constructor:

 public ClaimsPrincipal(IPrincipal principal) { this.m_version = "1.0"; this.m_identities = new List<ClaimsIdentity>(); if (principal == null) { throw new ArgumentNullException("principal"); } ClaimsPrincipal principal2 = principal as ClaimsPrincipal; if (principal2 == null) { this.m_identities.Add(new ClaimsIdentity(principal.Identity)); } else if (principal2.Identities != null) { this.m_identities.AddRange(principal2.Identities); } } 

This, in turn, as you can hope, returns a ClaimsIdentity , which wraps the main identifier (again, if it is not, in fact, ClaimsIdentity ).

When building ClaimsIdentity only place I can see where it will not set the authentication type (and thus create an identifier that is not authenticated) is here:

 if(identity is WindowsIdentity) { try { this.m_authenticationType = identity.AuthenticationType; } catch(UnauthorizedAccessException) { this.m_authenticationType = null; } } 

So, if the identifier that you Thread.CurrentPrincipal.Identity through Thread.CurrentPrincipal.Identity is actually an instance of WindowsIdentity , and in the context in which you are working, you have limited permissions, the constructed instance of ClaimsIdentity will have IsAuthenticated as false.

+9
source

All Articles