If you've done any research on the most recent website attacks performed by Lulzsec, Anonymous and the like, you'll probably have found out that they used very basic attack vectors such as RFI, XSS and CSRF.

This just goes to show that even top websites are not secure from such basic attacks, which is quite saddening if you think about it!

The purpose of this article (and probably a few more) is to teach you how to stop these attacks from happening on your own site. We will be discussing how to prevent CSRF attacks on your ASP.NET MVC website.

Luckily for us, the ASP.NET MVC framework provides an extremely simple way to avoid CSRF attacks.

 

Let's take a look at the default method signature for our Registration page:

   1         [HttpPost]

   2         public ActionResult Register(RegistrationModel model)

   3         {

   4             InitAccountTypes();

   5             if (ModelState.IsValid)

Now to add CSRF Protection to this form, our code now looks like this:

   1         [HttpPost]

   2         [ValidateAntiForgeryToken]

   3         public ActionResult Register(RegistrationModel model)

   4         {

   5             InitAccountTypes();

   6             if (ModelState.IsValid)

Simple, now we need to add something on the front-end that basically passes over our single-request based CSRF token, so in our form we add Html.AntiForgeryToken():

    1 @using (Html.BeginForm()) {

    2     @Html.AntiForgeryToken()

    3     <div>

That's it, we've now added CSRF protection by adding a one-time request token to our form, and ASP.NET MVC is automatically validating it on the server side when it is posted.