software

Validating .NET MVC 4 anti forgery tokens in ajax requests

Posted on Updated on

CSRF (Cross-Site Request Forgery) is an attack against a website “whereby unauthorized commands are transmitted from a user that the website trusts.” [Wikipedia]. Protection against this attack is essential for any modern web application.

In the case of .NET MVC, Microsoft have implemented an easy-to-use protection method against CSRF. There’s an attribute in the MVC framework that you can put on your controller actions: ValidateAntiForgeryToken. This works well, but it has a few disadvantages:

  1. You must manually decorate all your post actions with the attribute.
    It’s easy to forget to do this, so it’s preferable to decorate your entire controller with the attribute (or better yet, a base controller that your whole application uses). Unfortunately, this doesn’t work with the standard ValidateAntiForgeryToken attribute, as this causes all your GET actions to be validated as well (and they will always blow up, as the client doesn’t send any form data with a GET request).
  2. It doesn’t work with ajax posts.
    The standard attribute doesn’t work with ajax because it inspects the Request.Form collection when looking for the token field. When you’re making ajax posts this form is always empty. This is the reason I originally started looking for alternative implementations of the anti forgery token validation.

Read the rest of this entry »