ASP.NET MVC AntiForgeryToken and Caching
Asked Answered
M

1

11

I am currently working on an ASP.NET MVC project and came upon an error that seemed peculiar.

In the ASP.NET MVC Templates forms always get an AntiForgeryToken (thus leading me to believe that this is a best practice). However AntiForgeryTokens don't seem to work well with caching.

For example when I open a site with a form including an AntiForgeryToken and I duplicate the browser window both windows have the exact same AntiForgeryToken leading to an exception when posting the form. This problem does not exist when caching is disabled (via ActionFilter NoCache, see Disable browser cache for entire ASP.NET website).

So I guess my question is: Is this supposed to be that way? Is there any other way besides disabling the cache to tackle the problem?

Especially the fact that the default ASP.NET MVC templates contain AntiForgeryTokens but don't disable the cache (and therefore are open to the error described above) makes me wonder.

Thanks in advance!

Moncear answered 23/7, 2013 at 8:29 Comment(2)
Can you post your code and exact error? Html.AntiforgeryToken() generates a new token each time, so in two browser windows you should have different valuesLissome
Not if the browser doesn't query the server for the second browser window but uses its cache.Moncear
T
9

This is the expected behavior. Caching nicely caches the answer, including the value of the AntiForgeryToken. Disable caching on forms, and in particular on pages that use AntiForgeryToken. If you think about this further, if you're in a data-entry app, do you want to cache your data-entry forms? Probably not. However you do want to cache heavy reports -- even if it's just micro-caching -- a second or two.

Tyler answered 26/8, 2013 at 4:57 Comment(2)
What do you mean "Disable caching on forms"?Iridis
Any time you accept user input. Basically any time you have a <form> tag or an <input> tag.Tyler

© 2022 - 2024 — McMap. All rights reserved.