Message: ID4243: Failed to create SecurityToken. The token was not found in the token cache, and no cookies were found in the context

We get the same error as in this thread ... in our production environment. [ Caching WIF Security Tokens

Does anyone have a fix for this error? Message: ID4243: Failed to create SecurityToken. The token was not found in the token cache, and no cookies were found in this context.

Below is information about our setup:

• We use the built-in Windows Identity Framework with the .NET Framework 4.5.1

• The problem is almost always related to the change from RelyingParty # X to RelyingParty # Y (for example, the moment when the user presses RP # Y, he SIGNED OUT without asking about it) - when he logs in again after this event, he switched to the page he requested is inside RP # Y

• We use e.SessionToken.IsReferenceMode = true; // Cache on the server to get a smaller cookie

• Using IsReferenceMode = true, our FedAuth cookie stores a "pointer" to the actual token that is stored in our database

• We use our own DatabaseSecurityTokenCache, which overrides the functions in SessionSecurityTokenCache. Using DatabaseSecurityTokenCache together with IsSessionMode = true, we support the server farm (but we are also guaranteed to be on the same server through our entire login session), so if the application pool dies for some reason, we can get a token from the database through DatabaseSecurityTokenCache. I checked this by completely killing IIS in the middle of the session (with "net stop WAS" and restarting it again with "net start W3SVC", and we can still get the token from DatabaseSecurityTokenCache). I also tried to do the same, just using the ready-made SessionSecurityTokenCache package, and that would be unsatisfactory (as expected)

• The default token lifetime is 20 minutes (but the user can change it to 40 or 60 minutes if he wants) - this will only work the next time the user logs in (and 90% of our user just uses the default 20 minutes life)

• We use a certificate (the same on all servers) to encrypt the FedAuth cookie, not the machine key (which would be catastrophic when using a server farm with different machine keys)

• therefore, all servers can decrypt cookies that have been encrypted from another server.

• We have countdown javascript in our RelyingParty4 and RelyingParty5 (two different relying parties), which are used as a “script timeout” if the user leaves his computer unattended ... he will be signed when the token is about to expire - (minus) 30 seconds (for example, 20 minutes - 30 seconds = 19.5 minutes) from idle time. This will protect our very sensitive banking information, so when a user returns to his car, for example, we also use sliding sessions ([ http://www.cloudidentity.com/blog/2013/05/08/sliding-sessions-for- wif-4-5 /] ), and when we slide, the time in the javascript client is also updated to match the marker length minus 30 seconds. These 30 seconds are used to make sure that the session is still alive when you exit, so that it is slightly shorter than the token's lifetime / we are currently crawling if this condition is met: total lifetime / 2 .... for example, 20/2

• We only crawl if an action occurs with the user (ie, he moves, doing some work). We move per minute 10+ (if the token's lifetime is 20 minutes), as shown above,

• We debugged the problem several times, and this is the WIF error we receive: Exception: System.IdentityModel.Tokens.SecurityTokenException Message: ID4243: Failed to create SecurityToken. The token was not found in the token cache, and no cookies were found in the context. Source: Microsoft.IdentityModel at Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken (XmlReader reader, SecurityTokenResolver tokenResolver) at Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.Regent.Menetrement.ToerRename.ToerWeRenMenTerrentRename.ToerRenameRebTerMenTerrentRename ReadSessionTokenFromCookie (Byte [] sessionCookie) in the Microsoft.IdentityModel.Web.SessionAuthenticationModule.TryReadSessionTokenFromCookie (SessionSecurityToken & sessionToken) in the Microsoft.IdentityModel.Web.Session.ecentec.ecenter.quest.query eventquery eventquery eventquery Web.HttpApplication.IExecutionStep.Execute () in System.Web.HttpApplication.ExecuteStep (step IExecutionStep, Boolean and completed synchronously)

• We were able to re-create the error using the old FedAuth cookie and this plugin: (note! We are not sure that this is the same as happening on PROD, but at least it gives the same error in our logging system ) This is good, but I think you should add steps on how we can modify the contents of the FedAuth cookie to animate this problem locally .: It's just by taking the FedAuth cookie value from some previous sessions (on the same computer! Not with of another computer, this will not work) and pasting it into the FedAuth cookie value and refreshing the page .-

The plugin used to change the cookie in Chrome is called "Edit This Cookie": - If we change the contents of this cookie to the value from the previous session and press update (CTRL + R in Chrome), we will get the notorious TokenSecurityException ID4243, and RP - Challenges for unlimited FederatedSignout, because we cannot recover this situation.

Log off....

I should also mention that we took the Microsoft MSDN article labeled “Important” on IsReferenceMode and added it to our

SessionAuthenticationModule_SessionSecurityTokenCreated event:

e.SessionToken.IsReferenceMode = true;

taken from MSDN:

Attention! To operate in reference mode, Microsoft recommends providing the WSFederationAuthenticationModule.SessionSecurityTokenCreated event handler in the global.asax.cs file and setting the SessionSecurityToken.IsReferenceMode property to the token passed in the SessionSecurityTokenCreatedEventArgs.SessionToken property. This ensures that the session token is in link mode for each request and it is preferable to simply set the SessionAuthenticationModule.IsReferenceMode property in the session verification module.

Below is our entire SessionAuthenticationModule_SessionSecurityTokenReceived, consider the comments that I put into this ... it explains that everything does:

void SessionAuthenticationModule_SessionSecurityTokenReceived(object sender, SessionSecurityTokenReceivedEventArgs e) { if (e.SessionToken.ClaimsPrincipal != null) { DateTime now = DateTime.UtcNow; DateTime validTo = e.SessionToken.ValidTo; DateTime validFrom = e.SessionToken.ValidFrom; TimeSpan lifespan = new TimeSpan(validTo.Ticks - validFrom.Ticks); double keyEffectiveLifespan = new TimeSpan(e.SessionToken.KeyExpirationTime.Ticks - e.SessionToken.KeyEffectiveTime.Ticks).TotalMinutes; double halfSpan = lifespan.TotalMinutes / 2; if (validFrom.AddMinutes(halfSpan) < now && now < validTo) { SessionAuthenticationModule sam = sender as SessionAuthenticationModule; // This will ensure a re-issue of the token, with an extended lifetime, ie "slide". Id deletes the current token from our databasetoken cache (with overriden Remove of the SessionSecurityTokenCache ) and writes a new one into the cache with the overriden AddOrUpdate of the SessionSecurityTokenCache. // it will also write the token back into the cookie ( just the pointer to the cookie, because it stored in database-cache ) because the IsReferenceMode = True is set e.ReissueCookie = true; // Will force the DatabaseSecurityTokenCache'ið to clean up the cache with this, handler.Configuration.Caches.SessionSecurityTokenCache.Remove(key); internally in WIF SessioAuthenticationModule e.SessionToken = sam.CreateSessionSecurityToken( e.SessionToken.ClaimsPrincipal, e.SessionToken.Context, now, now.AddMinutes(lifespan.TotalMinutes), false); // Make persistent, þannig að kakan lifir EKKI af browser-close / tab-lokun: { e.SessionToken.IsReferenceMode = true; // Cache on server } // Not needed, because if ReissueCookie = true; is set, it WILL to a WriteSessionTokenToCookie internally in WIF //FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(e.SessionToken); // <---- er þetta etv bara það sem við þurfum ? Nei, á ekki að þurfa, er gert þegar tóki er búinn til með CreateSessionSecurityToken } else if (validTo < now) { // Fix // http://blogs.planbsoftware.co.nz/?p=521 var sessionAuthenticationModule = (SessionAuthenticationModule)sender; sessionAuthenticationModule.DeleteSessionTokenCookie(); // <--- is this really needed like the article says ? http://blogs.planbsoftware.co.nz/?p=521 e.Cancel = true; // This will allow a silent-login if the STS cookie is still valid, eg switching between RP where we're switching from an active RP to a RP which has it cookie outdated, but the STS session is still alive. We don't want to prompt the user for a new login, beucase the STS session is still OK! } } 
+6
source share
2 answers

this post helped me, so it can help you and others who have this kind of mistake.

 void Application_OnError() { var ex = Context.Error; if (ex is SecurityTokenException){ Context.ClearError(); if (FederatedAuthentication.SessionAuthenticationModule != null){ FederatedAuthentication.SessionAuthenticationModule.SignOut(); } Response.Redirect("~/"); } } 

From this link.

Hope this was helpful!

+6
source

---------- UPDATE, that's how Lord02 fixed the proposition -----------

The problem was that when users come with old cookies (from the previous session, that is, if they did NOT log out of our system ... but instead just closed the tab), and then logged in again, our cookie, which was in SessionMode = true ... tried to go to DatabaseTokenCache to get all the token from the database, but, as I said, our SSIS process removes all tokens that are older than 12 hours (obsolete tokens!), so we put on You have many orphan tokens, outdated in our database and unusual ... just for imayuschih in our database. Therefore, after this removal, the DatabaseTokenCache GET function will not return a valid token every night ... and the user was discharged due to: ID4243: SecurityToken could not be created. The token was not found in the token cache, and no cookies were found in this context.

Therefore, instead of NOT deleting tokens inside our database, I created a special handler that intercepts this error on the RP site ... and redirects the user back to STS - which will then create a new token and write this to the DatabaseTokenCacheStore database, as shown below

An exception with ID4243 is thrown when a cookie is set as "link mode" and the token is not in the cache - I can confirm that by design as well as by design, WIF does not redirect the STS call (to start the authentication process)

To overcome this problem, I catch this exception and respond appropriately. I redirect to the issuer if this error occurs inside the customSessionAuthModule created for this, created for this:

 public class CustomSessionAuthenticationModule : SessionAuthenticationModule { protected override void OnAuthenticateRequest(object sender, EventArgs eventArgs) { try { base.OnAuthenticateRequest(sender, eventArgs); } catch (SecurityTokenException exc) { // ID4243: Could not create a SecurityToken. A token was not found in the token cache and no cookie was found in the context. if (exc.Message.IndexOf("ID4243", StringComparison.OrdinalIgnoreCase) >= 0) { // Returning directly without setting any token will cause the FederationAuthenticationModule // to redirect back to the token issuer. return; } else { throw; } } } } 
+2
source

All Articles