Search code examples
.netasp.net-mvcazureasp.net-mvc-5antiforgerytoken

AntiForgeryToken creating issue in IE on F5 refresh while the site is deployed on Azure


Consider following as scenario in my ASP.NET MVC application:

View:

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

    @Html.LabelFor(m => m.FirstName)
    <br />
    @Html.EditorFor(m => m.FirstName)
    <br />
    @Html.LabelFor(m => m.LastName)
    <br />
    @Html.EditorFor(m => m.LastName)

    <br />
    <p>
        <input type="submit" title="Save" />
    </p>
}

Get Action:

[HttpGet]
public ActionResult Contact()
{
    return View();
}

Post Action:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Contact(Contact contact)
{
    ModelState.AddModelError("Test Exception", new Exception("An exception thrown by Submit button"));

    if (!ModelState.IsValid)        
         return View(contact);       

    return RedirectToAction("Manage");
}

Now, when I first press the submit button without providing the first name, it correctly shows a validation error. However, when I hit F5 to refresh the page, it first asks for confirmation of resending the information (which is expected in IE), but once I say, retry, it throws an error saying AntiFrogery key is not provided in the view.

This happens only in IE, and only if I try with the site deployed in Azure box.

Note, this works absolutely fine in my development environment with both Debug and Release profile, as well as after deploying on IIS also.

Any idea why this would be happening?


Solution

  • This is most likely happening because you are running on multiple instances and haven't specified a <machineKey> in the <system.web> section of your web.config. The <machineKey>. The validation cookies and tokens are encoded and decoded using a unique "machine key". This means that if you have a server farm (multiple instances), or change your server, your cookie will no longer be valid. The <machineKey> element looks like:

    <machineKey validationKey="DBB803BD7C3F11863BBA0AA7BCE555CB632587EEADE0A357830A1B792B0AE6203E11F5BF226427548CA0270BC913906CFCE526418258BA63BB772EB3103D7564" decryptionKey="2B92D5991197A746E221902F6D1588F194DC58CCD0AE78FC77B923825DFDFC6A" validation="SHA1" decryption="AES" />

    You can generate a unique one here - Generate ASP.NET Machine Keys.