Without Django Rest Framework, I used to create forms / POST requests like so:
<form id='loginForm' method="post" action="/register/">{% csrf_token %}
...
</form>
but I stared using Django Rest Framework and AngularJS on the frontend and I wasn't sure how to use the CSRF token, so I decided to do some research. I came across this website: http://blog.kevinastone.com/getting-started-with-django-rest-framework-and-angularjs.html and if you scroll down to the "Interlude: AngularJS + CSRF Protection" section, it says that I need to add the following script:
// Add the CSRF Token
var app = angular.module('example.app'); // Not including a list of dependent modules (2nd parameter to `module`) "re-opens" the module for additional configuration
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.common['X-CSRFToken'] = '{{ csrf_token|escapejs }}';
}]);
I then came across this SO post: Django csrf token + Angularjs which says that after adding
django.middleware.csrf.CsrfViewMiddleware
to my MIDDLEWARE_CLASSES is settings.py, all I need to add is the following lines
angular.module("myApp", [])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}])
Note that when I looked at other SO posts which explain how to do user authentication / registration using DRF and AngularjS (for example, this post: User Authentication in Django Rest Framework + Angular.js web app ) the answers do not include the lines:
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
With that said, what's the correct way to add CSRF Protection using Django Rest Framework and AngularJS?
Your second way ($httpProvider.defaults
) is probably the best way to do it. See the angular docs on http here. The xsrfCookieName
and xsrfHeaderName
options are relatively new in Angular. (I think they came in in 1.3, if memory serves...) So the other code you found probably just predated the newer, better way to do it. No need for a rendering or escape call in the template = cleaner code.