Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC AntiForgeryToken and Caching

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!

like image 875
chrischu Avatar asked Jul 23 '13 08:07

chrischu


People also ask

What is use of AntiForgeryToken in in ASP.NET MVC?

To help prevent CSRF attacks, ASP.NET MVC uses anti-forgery tokens, also called request verification tokens. The client requests an HTML page that contains a form. The server includes two tokens in the response. One token is sent as a cookie.

What are the different caching techniques available in .NET MVC?

Any (Default)- Content is cached in three locations- the Web Server, any proxy Servers and the Web Browser. Client- Content is cached on the Web Browser. Server- Content is cached on the Web Server. ServerAndClient- Content is cached on the Web Server and the Web Browser.

How does MVC AntiForgeryToken work?

Basically, when you request a page, the server includes a hidden field with an encrypted value. And when you submit the form, the website looks at the cookie to make sure you're authenticated, but it also looks at the encrypted value that the browser sends and make sure it's valid.

Why do we use AntiForgeryToken?

Using AntiForgeryToken helps mitigate against cross-site request forgery attacks. When you use it, your form will contain a hidden field and a corresponding cookie will also be set in the browser.


1 Answers

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.

like image 108
robrich Avatar answered Oct 07 '22 17:10

robrich