Louise Eggleton
Louise Eggleton

Reputation: 1009

Add Multiple Identities in ClaimsPrincipal

I see a lot of code like the following to create a new ClaimsIdentity and ClaimsPrincipal

var claims = new List<Claim>() {
new Claim(ClaimTypes.Name, "Me"),
new Claim(ClaimTypes.Email, "[email protected]"),
new Claim(ClaimTypes.Role, "Admin")
};

var id = new ClaimsIdentity(claims, "Forms");
var principal = new ClaimsPrincipal(id);

This is straightforward and there are lots of examples on the web about how to do this. What I would like to do and am not finding much documentation about is how to have multiple identities within ClaimsPrincipal. ClaimsPrincipal is defined like the following so clearly it supports multiple identities.

public class ClaimsPrincipal : IPrincipal
{
  public virtual IEnumerable<ClaimsIdentity> Identities { get; }
  ...
}

I am thinking that the above approach of declaring var principal = new ClaimsPrincipal(id) is not sufficient because I need to be able to add an identity to a ClaimsPrincipal that may already have an identity. So what happens if you already have an identity in ClaimsPrincipal and declare a new instance of ClaimsPrincipal? Do you now have two instances of ClaimsPrincipal with different identities? My hunch is that is the case, so instead I would need to check for the existence of the current ClaimsPrincipal and add to it like so:

ClaimsPrincipal principal;
if(System.Security.Claims.ClaimsPrincipal.Current != null)
{
   principal = System.Security.Claims.ClaimsPrincipal.Current;
   principal.AddIdentity(id)

}
else
{
   principal = new ClaimsPrincipal(id);
}

Am I on the right track here? Can anybody provide insight into what goes on under the hood when there are multiple identities in ClaimsPrincipal, If I am not on the right track can you offer suggestions on how I might go about using multiple identities within ClaimsPrincipal?

Upvotes: 5

Views: 6434

Answers (1)

paullem
paullem

Reputation: 1311

There is a constructor, which will do it for you:

public ClaimsPrincipal(IEnumerable<ClaimsIdentity> identities)

However, the semantics of this are undefined. Microsoft hasn't used it so far and I was never able to serialize it into an interoperable SAML token...... I am not sure what SesAM will do with it.

Upvotes: 2

Related Questions