For the past few days I've been reading about the windows identity foundation and how it's so good and flexible and built right into .net 4.5. Despite going over dozens of apis, blog posts, how-to's etc. I can't for the life of me get a simple implementation working.
I'm using windows authentication only and I can get the principal and view the claims that come with it (which is where every example seems to end). However I want to then transform them into useful claims and cache the results so that the transformation doesn't happen on every single request.
In my web.config I have:
<configSections>
<section name="system.identityModel" type="System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<section name="system.identityModel.services" type="System.IdentityModel.Services.Configuration.SystemIdentityModelServicesSection, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</configSections>
<system.identityModel>
<identityConfiguration>
<claimsAuthenticationManager type="SecurityProj.MyClaimsTransformationModule,SecurityProj" />
<claimsAuthorizationManager type="SecurityProj.MyClaimsAuthorizationManager,SecurityProj" />
</identityConfiguration>
</system.identityModel>
However the authentication manager never gets called. The only way I can get it to sort of work is by adding:
protected void Application_PostAuthenticateRequest()
{
ClaimsPrincipal currentPrincipal = ClaimsPrincipal.Current;
ClaimsTransformationModule customClaimsTransformer = new MyClaimsTransformationModule();
ClaimsPrincipal tranformedClaimsPrincipal = customClaimsTransformer.Authenticate(string.Empty, currentPrincipal);
HttpContext.Current.User = tranformedClaimsPrincipal;
}
To my global.asax.cs file. It works on the first request but then I get "Safe handle has been closed" errors after that and have no idea what is causing it. Clearly this isn't the correct way to do it, so does anyone know what a best or simply working practice is? This is just for windows authentication, I don't need anything more complicated than that.
For the caching, I was trying to use:
SessionSecurityToken token = FederatedAuthentication.SessionAuthenticationModule
.CreateSessionSecurityToken(
currentPrincipal,
"Security test",
System.DateTime.UtcNow,
System.DateTime.UtcNow.AddHours(1),
true);
if (FederatedAuthentication.SessionAuthenticationModule != null &&
FederatedAuthentication.SessionAuthenticationModule.ContainsSessionTokenCookie(HttpContext.Current.Request.Cookies))
{
return;
}
FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(token);
but I'm not sure about that part either and the transformation problems need to be fixed first.
Any help would be appreciated. Just need the lookup/transform to be called and a cookie set, thanks.
See Question&Answers more detail:os