Search code examples
.netauthenticationasp.net-core-mvcasp.net-identityclaims-based-identity

HttpContext.User.Claims vs HttpContext.User.Identities.Claims? Difference? When to use one over the other?


A HttpContext.User which is a ClaimsPrincipal has a collection of Claims, but the HttpContext.User also has a collection of ClaimsIdentity, which has a collection of claims and even the same properties like IsAuthenticated and Name.

What is the purpose or when to use one over the other, say in instances of user impersonation for admins? Or delegation? It seems like they are capable of tracking the same information in terms of roles and claims. If I want to have one user impersonate another, it seems like I could overwrite the HttpContext.User with the impersonated user and just store a value to indicate it's an impersonation and the original user, or maybe I could add the impersonated user to the ClaimsIdentities? Or something else?

I just don't know enough about this structure to determine the pros and cons or if there is a better way.


Solution

  • You can't use one over the other. If there is one ClaimsIdentity in the Identities property (the collection of ClaimsIdentity) then User.Identity will return that identity. This is easy to verify with a basic login capable app.

    enter image description here

    The Claims property will return all the claims for each identity in the Identities property. Trivially, if you just have one identity then you only get the claims in that identity.

    The basic idea behind having multiple identities is the same reason why you might carry a drivers license, bus pass, and work badge all in your wallet. Each identity gives you "access" to different areas and allow you to (legally) perform separate actions.