I\'m developing a DJANGO + AngularJS application, where the angular part is not being served by django.
I set the angular $httpProvider
as follows:
The 1.2.0 update wasn't sufficient for me when using Safari or Firefox (Chrome was working just fine all the time). The problem with Safari and Firefox was that the Django backend didn't send the csrf-cookie in the HTTP response.
What I had to do was add the @ensure_csrf_cookie decorator to my view function that builds up the page for Angularjs.
@ensure_csrf_token
def my_view(request):
...
and in the javascript file:
myApp.config(function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}
At least for now I have no idea why Chrome works without it but the other browsers don't.
very simple answer: it's only available from version 1.2.0, which is at the moment a release candidate.
Angular changes very frequently and some answers do not work with latest versions. In any way, since Angular expects a XSRF-TOKEN
cookie name, and sends a X-XSRF-TOKEN
header, we can alternatively simply tell Django to use these by default:
CSRF_COOKIE_NAME = 'XSRF-TOKEN'
CSRF_HEADER_NAME = 'HTTP_X_XSRF_TOKEN'
The first setting (see docs) is the cookie name for the csrf token, whereas the second one (see docs, only introduced in 1.9) is the respective header name.
Last, just for reference, do not forget to set:
CSRF_COOKIE_HTTPONLY = False
I had a similar issue and it was embarrassingly my fault.
My mistake:
$.post('/url', data)
Make sure you're using the $http
object!
$http.post('/url', data)
It was very easy to make this mistake since both seem to work equally as well as each other, except former does not look at $http.defaults.headers.common['X-CSRFToken']
, etc.
app.config(["$httpProvider", function($httpProvider) {
var csrfToken = getCookie('csrftoken');
$httpProvider.defaults.headers.common['X-CSRFToken'] = csrfToken;
}])
getCookie() take from https://docs.djangoproject.com/en/dev/ref/contrib/csrf/
Or set each method separately
$httpProvider.defaults.headers.post['X-CS....
$httpProvider.defaults.headers.get['X-CS....