[Dev Tip] All ASP.NET MVC Forms Need To Include Html.AntiForgeryToken() For Security


Having recently been implementing many new form pages in ASP.NET MVC, I’ve found myself over and over again adding the following two things to every form.

After Html.BeginForm() I Put @Html.AntiForgeryToken()
Add the Attribute [ValidateAntiForgeryToken] To Every Post Action Method
Before I was doing so much ASP.NET MVC, I would often see in Channel 9 videos, the presenter add the AntiForgeryToken() after the BeginForm() method on the cshtml razor page and say something like “you should always add this”. I never saw them say “and don’t forget to add the attribute ValidateAntiForgeryToken to the controller POST method.

Just to be clear, below is what I’m talking about:

image

image

What this does is to make sure that the trusted browser that go the original GET page is the same one that is delivering the POST message. Basically, this is all assuming that the end user is running a trusted browser. It’s more about protecting the end user and not the server. The idea is that a user who is using a browser they know is good (and trustworthy) will not be posting bad code back to the server. You can read more details here:

http://blog.stevensanderson.com/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/

https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet

If you look at the traffic in Chrome debug tools, you’ll notice an extra parameter on your form that the controller checks for as follows:


Hope this helps!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s