2013-05-20 - CSRF Token Security with Angular JS and backend framework

Lately, I have been playing with AngularJS (a javascript framework). AngularJS with the resource module is pretty good tool to consume REST api and render rich user interfaces. However, there is one thing difficult to solve while mixing AngularJS and Django (A python web framework) is how CSRF token is shared between the browser and the backend.

Both frameworks contains hardcoded keys to define the CSRF token name. This is quite annoying to post data and validate the source.

I resolved the issue on the AngularJS side by adding a default transformer on the HttpProvider service:

$httpProvider.defaults.transformRequest.push(function(data, headers) {
    // retrieve the injector instance for the PdfCutter module
    var injector = angular.injector(['pdfcutter', 'ng']);

    // attach the correct django CSRF Token for each ajax query
    if (injector.get('$cookies')['csrftoken']) {
        headers()['X-CSRFTOKEN'] = injector.get('$cookies')['csrftoken'];
    }

    return data;
});

Basically, the code retrieves the CSRF token from the backend on each Ajax request, and set the X-CSRFTOKEN header for later use.

This solution can be used on any web frameworks.

Comments

comments powered by Disqus