Persist Claims Transformation in a cookie with MVC and OWIN

Claims transformation (or claims augmentation as it’s sometimes called) in an MVC claims based application is “easy”. All you need is a simple piece of code:

 
Principal.Identity.AddClaim(new Claim(ClaimType, "ClaimValue")); 

Unfortunately, where you add that code isn’t.

Options

I found a number of options that worked, but didn’t behave in the way I needed.

Option 1 – use a custom ClaimsAuthenticationManager as detailed on MSDN.

Option 2 – add the above code into the Application_PostAuthenticateRequest method of Global.asax

Option 3 – if you’re using Owin, to create some Katana Middleware

Problem

The problem with all these solutions is the number of times the transformation takes place, i.e. how often that code is executed.

Why would you care about the number of times it’s called? In all the examples I found, you wouldn’t, as “magic strings” are being added to the claims, and therefore it’s really fast. In my case, and I’d imagine most real world cases, you’re likely to be making an IO bound call to a database or web service to lookup the extra claim. You really don’t want to be doing that every single page hit.

Solution

I eventually hit upon the solution with the thanks to a StackOverflow post which hinted at using the OnResponseSignIn of the CookieAuthenticationProvider

 
Provider = new CookieAuthenticationProvider() 
{ 
    OnResponseSignIn = async context => 
    { 
         // Apply Claims Transformation here
    } 
}  

The OnResponseSignIn is the last chance you have to transform the ClaimsIdentity before it is serialized into a cookie during sign in. The code is only executed once, so no need to be concerned about performance when making a call to a lookup service.

Leave a Reply

Your email address will not be published. Required fields are marked *