CSRF (ASP.NET MVC): Code Review – ValidateAntiForgeryToken

Before we look at code reviewing for CSRF

To code review for CSRF across a lot of files the fastest way is to search in your .cs files for [HttpPost] and then make sure [ValidateAntiForgeryToken] appears below the attribute. Note this assumes that only “posts” change data and “gets” simply retrieve data.

Something like:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(MyClass myClass)

{

///etc

 

Then you know your view must also contain the anti forgery token (in order for the form to post data at all)

@using (Html.BeginForm()) {

@Html.AntiForgeryToken() //// For more details see  CRSF – Cross Site Request Forgery.

 

Regarding the comment – “Note this assumes that only “posts” change data and “gets” simply retrieve data“. Also skim your controllers for any actions with names that sound like a post, for instance “SaveItem”. “SaveItem” sounds like something that changes data and should be marked as [HttpPost] and then have a [ValidateAntiForgeryToken] attribute added as well.

Skimming files is actually pretty quick and you can easily eliminate the majority of problems. Doing this earlier and continually during the development process (as with everything) is cheaper than waiting until the last minute and breaking functionality the week before going live. Unfortunately there is no substitute for checking every line of code but it is easier if you know the sorts of things to look for

 

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s