Dealing with session token exceptions with WIF in ASP.NET

When doing WIF programming in ASP.NET you will sometimes come across this exception:

“ID4243: Could not create a SecurityToken. A token was not found in the token cache and no cookie was found in the context.”

This exception is thrown when the browser is sending a cookie that contains the user’s claims but something about the processing can’t be performed (either the key has changed so the token can’t be validated or if using a server side cache and the cache is empty). An end user isn’t going to be able to do much about this and they’re going to continue to get the error since the browser will keep sending the cookie.

The easy solution to the problem is to add this snippet to the OnError event in global.asax:

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

This detects the token exception and clears the cookie. You could also add logging and have other logic about where to redirect the user (perhaps back to a login page if desired).

HTH

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s