How do you use IPrincipal and IIdentity in the portable class libraries?

2.8k views Asked by At

With WIF (Windows Identity Foundation) 4.5, Microsoft created the WindowsPrincipal class, which is a type of ClaimsPrincipal. Of course, these classes aren't portable, but the interfaces behind them are (IPrincipal). The same can be said of the ClaimsIndentity class implementing the IIdentity interface.

The problem I have is that these classes, and WIF in general is based entirely on the concept of "claims", which is awesome... but the two interfaces, IPrincipal and IIdentity are not. Not only that, but the ClaimsPrincipal class also has a collection of Identities instead of just a single Identity associated to it.

  • IPrincipal has Identity and IsInRole members.
  • IIdentity has AuthenticationType, IsAuthenticated, and Name members.

Given the fact that the Portable Class Libraries can only access these two interfaces, how does one go about getting the actual claims?

Also, in the rare instance that a principal has multiple identities, how does one get the "non-primary" identities?

1

There are 1 answers

1
johnnyno On

Microsoft provided claims aware types in Microsoft.IdentityModel.dll which is not portable (yet, I hope). Those types just extends current identity types e.g. IPrincipal:

public interface IClaimsPrincipal : IPrincipal

It means that claims aware types are compatibile with old code which uses IPrincipal and IIdentity interfaces. But to make your code claims aware you must add a reference to Microsoft.IdentityModel.dll (which is not available as a PCL) or write it from scratch.

If you want to test how old code behaves when processing instances of claims aware types, you can just use downcasting to the IPrincipal interface:

IClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(new List<IClaimsIdentity>()
{
    new ClaimsIdentity("AuthType1"),
    new ClaimsIdentity("AuthType2")
});

IPrincipal principal = claimsPrincipal as IPrincipal;
IIdentity identity = principal.Identity;