Monday, January 18, 2010

ajax requests with django 1.2 csrf

I'm looking forward to using the new features of django 1.2, but I needed to figure out how to update my applications for using the new, more secure, csrf protection system.

For form requests, it's simple to add {% csrf_token %} after each <form> element in templates. You just want to make sure that the target of the form isn't an external site. There's a nice script in the extras directory to help you find forms (csrf_migration_helper.py).

For ajax requests, that is, for requests using XMLHttpRequest, I had to add the X-Requested-With: "XMLHttpRequest" header to my requests over http. Here's a snippet which does this in javascript:


// First, get an XMLHttpRequest object in a browser independent way.
var req = getXMLHttpRequest(); //from MochiKit in my case
req.open("POST", url,true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.setRequestHeader('X-Requested-With' , 'XMLHttpRequest');


setRequestHeader() is a standard method of XMLHttpRequest. One thing that's interesting is that this header addition is not required (at least in version 1.2alpha) when sending the request over https.