Since V1 of .NET there is a “slot” to store authorization information about the current user: Thread.CurrentPrincipal. This data gets propagated to newly created threads and is deeply integrated into other application frameworks like ASP.NET.
To integrate claims into ASP.NET it makes sense to re-use this infrastructure.
To accomplish this the AuthorizationContext has to be wrapped by an IPrincipal implementation. I called mine IdentityPrincipal (which is part of LeastPrivilege.IdentityModel). I won’t show you the source code here because this is not very exciting – but there are some things to note:
- You can either new up the class by supplying a concrete AuthorizationContext or a list of claim sets.
- If none of the above are specified, the class will try to use ServiceSecurityContext (for WCF support).
- You can pass in one of the built-in IIdentity implementations (like WindowsIdentity, FormsIdentity etc). If you don’t, the identity will be anoynmous (and it is assumed that you don’t care about it).
- I also created a ClaimsIdentity which simply wraps a claim and uses the resource as the Name property.
- It features a static IdentityPrincipal.Current property which grabs the IPrincipal from Thread.CurrentPrincipal and tries to cast it to IdentityPrincipal.
- The IsInRole implementation searches for a configurable claim type in the claim sets. Then the resource gets checked against the supplied “role name”. This gives you compatibility for existing role based authorization code like ASP.NET UrlAuthorization (for simple scenarios).
The typical pattern would be:
- Create an AuthorizationContext (or just one or more claim sets).
- New up an IdentityPrincipal and put it on Thread.CurrentPrincipal (or Context.User for ASP.NET)
- Call Thread.CurrentPrincipal.IsInRole (or Context.User.IsInRole) for simple checks
- Call IdentityPrincipal.Current to get access to the claim sets and use the previously described extension methods for more advanced claims checking.
I updated the source download here to include the IdentityPrincipal as well as a console and WCF test app.