1

I have an angular form that I want to submit via post request to my django backend. Regular wisdom for this is to use the following trick on your angluar app:

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

However, this requires your cookies are javascript accessible. How do you make post requests from angular to django work when you have the django setting CSRF_COOKIE_HTTPONLY = True?

Note that this question could also be for how to use angular with django session-based csrf tokens (such as with https://github.com/mozilla/django-session-csrf), since this has the same problem of angular not being able to access the crsf token from the cookie.

Zags
  • 37,389
  • 14
  • 105
  • 140

1 Answers1

2

Disclaimer: This answer works with Django up through 1.9 or if you are using a separate angular app on each page. This is because Django 1.10 changed the CSRF middleware to change the token after every request. For single page angular apps running on Django 1.10+, please see Pass Django CSRF token to Angular with CSRF_COOKIE_HTTPONLY

Answer:

Somewhere in your template, attach the csrf token to your window:

<script type='text/javascript'>
    window.csrfmiddlewaretoken = "{{ csrf_token }}";
</script>

Then, you can set the csrf token directly on the header of post requests without needing the cookie:

angularApp.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.headers.post["X-CSRFToken"] = window.csrfmiddlewaretoken;
}]);
Community
  • 1
  • 1
Zags
  • 37,389
  • 14
  • 105
  • 140