MVC ValidateAntiForgeryToken multi-tabs problem

前端 未结 3 1250
我在风中等你
我在风中等你 2021-02-10 06:01

We\'d been getting \"A required anti-forgery token was not supplied or was invalid.\" errors, and on some further investigation, I\'ve managed to recreate the problem in its sim

相关标签:
3条回答
  • 2021-02-10 06:19

    Looking at the MVC 2 source code it looks like the AntiForgeryToken hidden field includes the User.Identity.Name serialized, if your signed in. In line 69 of the ValidateAntiForgeryTokenAttribute it seems to then check your token with the current User.Identity.Name.

        string currentUsername = AntiForgeryData.GetUsername(filterContext.HttpContext.User);
        if (!String.Equals(formToken.Username, currentUsername, StringComparison.OrdinalIgnoreCase)) {
            // error: form token is not valid for this user
            // (don't care about cookie token)
            throw CreateValidationException();
        }
    

    Because in your other tab you are now signed in the code above invalidates the existing token which doesn't contain the User.Identity.Name.

    This could be fixed by adding a !string.IsNullOrEmpty(formToken.Username) around that check but I don't know if that will open up security issues plus it means having a custom MVC 2 Build.

    0 讨论(0)
  • 2021-02-10 06:22

    You could use the same salt:

    <% using(Html.BeginForm("SignIn", "Home", FormMethod.Post)) {%>
        <%= Html.AntiForgeryToken("123")%>
        <input type="submit" value="Sign in" />
    <%}%>
    
    <% using(Html.BeginForm("Protected", "Home", FormMethod.Post)) {%>
        <%= Html.AntiForgeryToken("456")%>
        <input type="submit" value="Do secret stuff" />
    <%}%>
    

    And in your controller:

    [ValidateAntiForgeryToken(Salt = "123")]
    public ActionResult SignIn()
    {
        ViewData["status"] = "Signed In!";
        FormsAuthentication.SetAuthCookie("username", false);
        return View("Index");
    }
    
    [Authorize]
    [ValidateAntiForgeryToken(Salt = "456")]
    public ActionResult Protected()
    {
        ViewData["status"] = "Authed";
        return View("Index");
    }
    

    Do the same with the other token but make sure to pick a different salt.

    0 讨论(0)
  • 2021-02-10 06:24

    The real answer to this problem is simply that you shouldn't use an anti-forgery token on login forms!

    It's pointless to "forge" being a user on a login form - they aren't logged in!

    0 讨论(0)
提交回复
热议问题