1

Using MVC 5.1.1/VS 2013 Professional/.Net 4.5

I keep getting error once in a while (from localhost and from production IIS 7):

System.Web.Mvc.HttpAntiForgeryException: The anti-forgery cookie token and form field token do not match.

The issue seems to be when i logout a user, sometimes when i go to authenticate again thats when i get the error.

My authentication code looks like something like this:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginViewModel model)
    {
        if (ModelState.IsValid)
        {

            var user = _uow.UserRepository.FindLogin(model.Email, model.Password);
            if (user != null)
            {
                var claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.Email, user.Email));
                claims.Add(new Claim(ClaimTypes.NameIdentifier, user.UserID.ToString()));
                claims.Add(new Claim(ClaimTypes.Role, user.UserLevel.ToString()));

                var id = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

                var ctx = Request.GetOwinContext();
                var authenticationManager = ctx.Authentication;

                authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, id);

            }
            else
            {
                ModelState.AddModelError("", "Invalid Email Address or Password.");
            }
        }


        return View(model);
    }

Update with LogOut Method:

    [HttpGet]
    [AllowAnonymous]
    public ActionResult LogOut(LoginViewModel model)
    {
        Session.Abandon();
        return SignOffUser();
    }

    private ActionResult SignOffUser()
    {
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
        return RedirectToAction("Index", "Home");
    }

LogOut Form View

@if (Request.IsAuthenticated)
{
    using (Html.BeginForm(null, null, FormMethod.Post, new {id = "logoutForm", @class  = "navbar-right"}))
    {
        @Html.AntiForgeryToken()
        ....

    }
}
DavidJS
  • 417
  • 2
  • 5
  • 16

3 Answers3

0

Show your logout form(view).

This happens if you are calling the logout method in your controller from your view but don't have antiforgerytoken generated inside the form.

Your form should look like

@using(Html.BeginForm("Action","Controller"))
{
   @Html.antiforgerytoken()
   ....
}

Then the action you call via your view should look like

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult MyAction()
{
   return content("hello user! Antiforgerytoken has been validated1");
}

PS: No matter what action method your form calls, if you want to have antiforgery token that needs to be validated, then the form and action method should look like what I've mentioned above.

Cybercop
  • 8,475
  • 21
  • 75
  • 135
0

Another thing you may want to look at is that on your logout page, you don't necessary validate the forgery token.

Try changing this:

[HttpGet]
[AllowAnonymous]
public ActionResult LogOut(LoginViewModel model)
{

To this

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult LogOut(LoginViewModel model)
{

My bet is that the token is changing on the page, and since it's not validated, ASP.NET doesn't know if it is truly correct or not.

E: just noticed, it should actually be an httppost on logout

Dylan Corriveau
  • 2,561
  • 4
  • 29
  • 36
0

Try setting explicitly machine key in web.config (under system.web):

 <machineKey validationKey="971E32D270A381E2B5954ECB4762CE401D0DF1608CAC303D527FA3DB5D70FA77667B8CF3153CE1F17C3FAF7839733A77E44000B3D8229E6E58D0C954AC2E796B" decryptionKey="1D5375942DA2B2C949798F272D3026421DDBD231757CA12C794E68E9F8CECA71" validation="SHA1" decryption="AES" />

Here's a site that generate unique Machnie Keys http://www.developerfusion.com/tools/generatemachinekey/

link: The anti-forgery cookie token and form field token do not match in MVC 4

Community
  • 1
  • 1
pajics
  • 2,938
  • 3
  • 23
  • 27