Month: February 2013
The Eight Queens problem
My colleague recently introduced me to the eight queens problem (you can read more about it over at Wikipedia). In summary, you have to be able to place eight queens down on a chess board without any of them attacking any other.
This sounds easy at first, but I found that taking a few guesses on a piece of paper yielded no results. Rather than simply solving the problem, I decided it would be more fun to write a program that would find all the solutions for me. I’d been looking for a nice little programming problem to teach myself F# for a while, so I thought I’d give this a go. Well, after a few false starts and a lot of F# Googling, here’s my solution:
Validating .NET MVC 4 anti forgery tokens in ajax requests
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:
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).
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.