[Answered ]-Django authentication : CSRF Failed

2👍

Why are you using $httpProvider.defaults.headers.common['X-CSRFToken'] = getCookie('csrftoken');? I’m not an AngularJS expert, but that line shouldn’t be needed.

This is what the Django documentation says:

If you’re using AngularJS 1.1.3 and newer, it’s sufficient to configure the $http provider with the cookie and header names:

$http.defaults.xsrfCookieName = 'csrftoken';
$http.defaults.xsrfHeaderName = 'X-CSRFToken';

From my understanding, this is how your code should look like:

$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
/* Not needed, causes harm! */
/* $httpProvider.defaults.headers.common['X-CSRFToken'] = getCookie('csrftoken'); */
console.log($httpProvider.defaults.headers.common);

This should also explain why with X-CSRFToken: null is working.

0👍

If I’m not mistaken Django’s CSRF have a timeframe where they are working.

From time to time I do have this issue and refreshing the form and therefore the CSRF does work for me.

Leave a comment