MVC 4 provided anti-forgery token was meant for user “” but the current user is “user”

家住魔仙堡 提交于 2019-11-29 09:11:50
ganders

I believe this is occurring because the users are double-clicking the submit button on the form. At least that's EXACTLY the case on my site.

Troubleshooting anti-forgery token problems

Mohsen Esmailpour

The validation code that runs against an AntiForgeryToken also checks your logged in user credentials haven’t changed – these are also encrypted in the cookie. This means that if you logged in or out in a popup or another browser tab, your form submission will fail with the following exception:

System.Web.Mvc.HttpAntiForgeryException (0x80004005):
The provided anti-forgery token was meant for user "", but the current user is "SomeOne".

You can turn this off by putting AntiForgeryConfig.SuppressIdentityHeuristicChecks = true; in Application_Start method inside Global.asax file.

When a AntiForgeryToken doesn’t validate your website will throw an Exception of type System.Web.Mvc.HttpAntiForgeryException. You can make this a little easier by at least giving the user a more informative page targeted at these exceptions by catching the HttpAntiForgeryException.

private void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();

    if (ex is HttpAntiForgeryException)
    {
        Response.Clear();
        Server.ClearError(); //make sure you log the exception first
        Response.Redirect("/error/antiforgery", true);
    }
}

More info:

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

Html.AntiForgeryToken – Balancing Security with Usability

I had the same problem when

  • User logs in
  • Then on the Home Page the User hits Back Button to go back to Login
  • User logs in as a different User
  • This gave the exception : The provided anti-forgery token was meant for user "" but the current user is "user"

I found this was happening only in IE and I fixed it by doing a couple of things

  1. Disabled output caching for the login page, because in debug mode I found that hitting the back button did not generate a new request to the Login page
  2. On the login page I added a check to see if the user is already authenticated, and if so logged out the user, and then redirected to the Login page again.

    [AllowAnonymous]
    [OutputCache(NoStore=true, Location=System.Web.UI.OutputCacheLocation.None)]
    public ActionResult Login)
    {
        if (HttpContext.Request.IsAuthenticated)
        {
            WebSecurity.Logout();
            Session.Abandon();
            return RedirectToAction("Login");
        }
    
        return View();
    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!