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

后端 未结 3 2090
别那么骄傲
别那么骄傲 2020-12-18 18:24

I\'ve recently put Live a web application which was built using MVC 4 and Entity Framework 5. The MVC application uses

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-18 19:11

    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

提交回复
热议问题