Have seen Dominick Baier's videos on Pluralsight and most of this I got from there. I'm trying to do a claims transformation in .net 4.5, MVC. After a lot of messing around I can get the claims transformed, but can't get them to persist. If I just have it run my ClaimsTransformer every time no problem, but this is hitting a database so I want to cache these.
So here's what I did
class ClaimsTransformer : ClaimsAuthenticationManager
{
public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
{
if (!incomingPrincipal.Identity.IsAuthenticated)
{
return base.Authenticate(resourceName, incomingPrincipal);
}
ClaimsPrincipal transformedPrincipal = incomingPrincipal;
I then perform some database access add new claims to transformedPrincipal. Then create a new principal (probably don't need this additional instantiation but others seemed to do it), write this out:
ClaimsPrincipal newClaimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(transformedPrincipal.Claims, "ApplicationCookie"));
if (HttpContext.Current != null)
{
// this caches the transformed claims
var sessionToken = new SessionSecurityToken(newClaimsPrincipal, TimeSpan.FromHours(8));
FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionToken);
}
return newClaimsPrincipal;
I can see the new claims here in newClaimsPrincipal. To force the transformation to get called I am using ClaimsTransformationHttpModule from the ThinkTecture guys and can verify that this code gets run:
context.User = transformedPrincipal;
HttpContext.Current.User = transformedPrincipal;
Thread.CurrentPrincipal = transformedPrincipal;
And my additional claims are part of the transformedPrincipal.
So looks fine - but when subsequent requests come in I don't have the additional claims. ClaimsTransformer is not called, as expected, but I only have the initial set of claims - not those added by my transformation.
After logging out, my additional claims are persisted. This is using the new Visual Studio 2013 basic MVC template with Identity 2.0etc.
What I think is happening is the login runs first:
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
and this writes the authentication cookie, before my claims are transformed. Following this my claimstransformer runs and writes its own authorization cookie so now I have two. When I logout the first one's claims are lost and not the second one's claims become active.
Am confused.com.
Thanks Ray