Problems using anti-forgery token

ASP.Net MVC provides an anti-forgery mechanism using the methods @Html.AntiForgeryToken() and the [ValidateAntiForgeryToken] attribute.

I developed a web application using this mechanism for login, as the MVC template automatically provides this code. It worked fine using Chrome, but when I tried out the application in Internet Explorer, a couple of errors occurred relating to it:

Anti-forgery token is meant for user “” but the current user is “username”

The provided anti-forgery token was meant for a different claims-based user

The different answers on SO and various blogs offered no solution:

  • setting AntiForgeryConfig.SuppressIdentityHeuristicChecks to true
  • exchanging the anti-forgery token
  • changing AntiForgeryConfig.UniqueClaimTypeIdentifier

The solution that finally worked destroys the current ASP.Net session and signs out if the user is currently logged in:

[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
  Session.Abandon();
  if (AuthenticationManager.User.Identity.IsAuthenticated)
    AuthenticationManager.SignOut();
  ViewBag.ReturnUrl = returnUrl;
  return View();
}
Advertisements

One Response to Problems using anti-forgery token

  1. ozbob says:

    Nice solution, but I put the following on the Login view: if Authenticated “you are already loggedin”, and a Logout button.

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

%d bloggers like this: