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

tcode picture tcode · Dec 2, 2013 · Viewed 37.5k times · Source

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

I noticed using Elmah that when users are logging into the application, sometimes they are getting the following error

The provided anti-forgery token was meant for user "" but the current user is "user"

I've done a bit of research already on how to fix this issue, but nothing seems to work for me. Please see my Login View and corresponding Controller Actions below.

Razor View

@if (!HttpContext.Current.User.Identity.IsAuthenticated)
{

using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

     <div class="formEl_a">

        <fieldset>
            <legend>Login Information</legend>

            <div class="lbl_a">
                Email
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.Email, new { @class = "inpt_a" })<br />
                @Html.ValidationMessageFor(m => m.Email)
            </div>

            <div class="lbl_a">
                @Html.LabelFor(m => m.Password)
            </div>
            <div class="editor-field sepH_b">
                @Html.PasswordFor(m => m.Password, new { @class = "inpt_a" })<br />
                @Html.ValidationMessageFor(m => m.Password)
            </div>


        </fieldset>
    </div>
    <br />
      <p>
            <input type="submit" value="Log In" class="btn btn_d sepV_a" />
        </p>

}    
}

Controller

[AllowAnonymous]
public ActionResult Login()
{
     return View();
}

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
     if (ModelState.IsValid && _accountService.Logon(model.Email, model.Password, true))
     {
          //Validate
     }
     else
     {
          // inform of failed login
      }

}

I thought this all looked OK, but still the error persists. Does any have any ideas on how to fix this problem?

Your help is greatly appreciated.

Thanks.

Answer

ganders picture ganders · Nov 25, 2014

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