Intermittent error thrown, "A required anti-forgery token was not supplied or was invalid."

Dave K picture Dave K · May 7, 2010 · Viewed 7.9k times · Source

I'm occasionally getting this error during normal use, and I've not found a way to stop it without removing the attribute that requires the token, which I'd rather not do.

I've gotten this bug during my own testing (but seemingly randomly) and I know from my logging that actual logged-in users are getting it as well.

Does anyone know what would cause the antiforgerytoken system to break (other than a real attack), and how I could fix this without opening up a security hole in my forms?

Thanks!

Answer

Scott Rippey picture Scott Rippey · Nov 8, 2011

Here's a portion of my answer to a similar question:

Machine Key and Cookies: this issue is ugly, easy to spot (causes exceptions), but not very intuitive. The validation cookies and tokens are encoded and decoded using a unique "machine key". This means that if you have a server farm, or change your server, your cookie will no longer be valid. Closing your browser fixes the issue (because the cookie is a session cookie). However, some people leave their browser windows open in the background for a long time!
The solution is to set a "machine key" in your config file. This will tell MVC to use the same key on all servers, ensuring that the cookie will be decryptable everywhere.

Please note: if a user keeps any browser window open, even AFTER you change your machine key, they will continue to get these error messages! They MUST close the window (to clear the session-cookie) in order to access your website again.