Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect type of ClaimsIdentity read from session cookie after recycling of worker process

In a VS 2012 / .NET 4.5 / ASP.NET MVC 4 application I have a custom identity type derived from ClaimsIdentity. It just adds a few readonly properties to the base class that read values from some claims for convenience:

public class AppIdentity : ClaimsIdentity
{
    public AppIdentity(IEnumerable<Claim> claims) : base(claims, "Custom")

    public string CustomProp { get { return FindFirst("CustomClaim").Value; } }
    // etc.
}

In a custom ClaimsAuthenticationManager I convert the incoming principal into a principal that wraps the above identity, create a token for this principal and write the token to a cookie:

var claims = new List<Claim>
{
    new Claim("CustomClaim", "CustomValue"),
    // etc.
};
var newPrincipal = new ClaimsPrincipal(new AppIdentity(claims));
var sessionToken = new SessionToken(newPrincipal, TimeSpan,FromHours(24));
FederatedAuthentication.SessionAuthenticationModule
    .WriteSessionTokenToCookie(sessionToken);

If I fetch the identity for subsequent requests in a controller action like so...

var identity = ClaimsPrincipal.Current.Identity;

...I find that sometimes the runtime type of identity is AppIdentity and sometimes it is only its base type ClaimsIdentity. My custom claims are always present inside of the Claims collection of identity.

The identity seems to "lose" the type AppIdentity that I expect when the worker process gets recycled. I'm only using an IIS Express development server in this project at the moment and I can force this behaviour when I do a small change in web.config for example. After that the identity always has the type ClaimsIdentity and not AppIdentity anymore.

Question: Is this approach to save a custom claims identity type in a cookie wrong and possibly not supported? Does a session cookie store the type information of a derived ClaimsIdentity at all (which would be necessary, I guess, to materialize the correct identity type from the cookie)?

like image 215
Slauma Avatar asked Dec 07 '25 00:12

Slauma


1 Answers

The type identity gets lost during serialization roundtrips. I wrote about it here: http://leastprivilege.com/2012/10/08/custom-claims-principals-in-net-4-5/

like image 199
leastprivilege Avatar answered Dec 08 '25 13:12

leastprivilege



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!