jrief / django-angular

Let AngularJS play well with Django
http://django-angular.awesto.com/
MIT License
1.23k stars 293 forks source link

CSRF protection, update docs #143

Closed jkosir closed 9 years ago

jkosir commented 9 years ago

The docs suggest manually setting the X-CSRFToken header on post requests:

var my_app = angular.module('myApp', [/* other dependencies */, 'ngCookies']).run(function($http, $cookies) {
    $http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
});

This only works for POST (and not delete/put) and requires ngCookies. Angular already has xsrf support, but it uses different names for cookie and headers, XSRF-TOKEN and X-XSRF-TOKEN. Both can be easily changed to what django uses:

.config(function ($httpProvider) {
    $httpProvider.defaults.xsrfCookieName = 'csrftoken';
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
});

This is enough for angular app to work with django's csrf protection (also works for post/put/delete) and doesn't have the ngCookies dependency, so I suggest we update the docs to this.

jrief commented 9 years ago

sounds good - but where do we get the secret from? Or did I miss something here?

Thats's why I added the templatetag {% csrf_value %}. See also http://django-angular.readthedocs.org/en/latest/csrf-protection.html#set-header-with-x-csrftoken-via-templatetag

jkosir commented 9 years ago

Angular reads the cookie value automatically with these settings, no need to set headers manually.

The {% csrf_value %} approach is a bit safer, so I guess we could keep that and only change the ngCookies part.