I have an ActionResult decorated with ValidateAntiForgeryToken and Authorize. Once my forms authorization timeout limit is reached, I’m receiving a “A required anti-forgery token was not supplied or was invalid” error instead of being routed to my login page.
Can someone explain why this happens?
The
ValidateAntiForgeryTokenAttributeto quote MSDN. What
Html.AntiForgeryToken()does is output a hidden field into the form, something like:<input name="__RequestVerificationToken" type="hidden" value="XXX" />.What the
ValidateAntiForgeryTokenAttributedoes on post back is compare the posted value to a previously stored cookie, to verify that they match. See http://aspnet.codeplex.com/SourceControl/changeset/view/72551#338576 (theOnAuthorizationmethod) for details. The cookie has a name of RequestVerificationToken_Lw (you can use a cookie inspection tool like FireCookie to see this).The cookie stored is a session cookie (the important bit). This means that when your authorization timeout is reached (30 mins by default in .NET), the cookie expires, doesn’t get sent with the next request and the comparison to the hidden field value fails, throwing a
HttpAntiForgeryException.