[PYTHON] How to resolve CSRF Protection when using AngularJS with Django

Overview

When I post with AngularJS's HttpProvider for an endpoint created with Django's standard View or Django REST framework, I get a 403 error. Come on.

$http.post('/api/entries', {'title': 'diary', 'body': 'It is a good weather today'})

Response

{detail: "CSRF Failed: CSRF token missing or incorrect."}

Cause

This is because I haven't been able to get around Django's CSRF Protection well, regardless of using AngularJS.

It seems that the value of Request Header that stores CSRF Token is different between the value used by AngularJS by default and the value recognized by Django.

If you read the following documentation, Django will have to send the value of csrftoken with the header name X-CSRFToken when making an Ajax request.

Cross Site Request Forgery protection | Django documentation | Django

solution

AngularJS's HTTPProvider has an option to change the behavior of CSRF Protection, and if you specify this, you can change the header name when sending the CSRF Token and the key of the cookie to be referenced.

[AngularJS: API: http](https://docs.angularjs.org/api/ng/service/http#cross-site-request-forgery-xsrf-protection)

To make settings for Django, set as follows.

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

Now AngularJS will automatically interpret and send the csrftoken without you having to do anything. Congratulations.

Digression

There's one more addiction to using AngularJS with Django, and AngularJS's variable expansion conflicts with Django's template engine, so you can't do variable expansion by default.

You can be happy if you change the symbol by referring to the following.

How to resolve variable scope conflicts between AngularJS and jinja2 --Qiita

Recommended Posts

How to resolve CSRF Protection when using AngularJS with Django
[Django] How to resolve errors when installing mysqlclient
How to deal with SessionNotCreatedException when using Selenium
How to handle static files when deploying to production with Django
How to not load images when using PhantomJS with Selenium
How to get started with Django
How to authenticate with Django Part 2
How to authenticate with Django Part 3
[Tips] How to do template extends when creating HTML with django
How to do arithmetic with Django template
How to deal with errors when hitting pip ②
How to develop a cart app with Django
How to implement "named_scope" of RubyOnRails with Django
How to access with cache when reading_json in pandas
When you want to filter with Django REST framework
How to exit when using Python in Terminal (Mac)
How to analyze with Google Colaboratory using Kaggle API
Things to do when you start developing with Django
Things to watch out for when migrating with Django
How to write faster when using numpy like deque
Model.objects.extra to consider before using raw SQL with Django
How to deal with "Type Error: No matching signature found" error when using pandas fillna
When using optparse with iPython
Eliminate errors that occur when using Django REST Swagger with Django 3.0
How to reset password via API using Django rest framework
How to check ORM behavior in one file with django
How to update user information when logging in to Django RemoteUserMiddleware
How to update with SQLAlchemy?
[Django] How to give input values in advance with ModelForm
DEBUG settings when using Django
How to cast with Theano
How to generate a query using the IN operator in Django
[Linux] How to deal with garbled characters when viewing files
How to Alter with SQLAlchemy?
How to separate strings with','
Things to keep in mind when using Python with AtCoder
How to deal with the terminal getting into the pipenv environment without permission when using pipenv with vscode
How to RDP with Fedora31
Things to keep in mind when using cgi with python.
How to update FC2 blog etc. using XMLRPC with python
How to deal with UnicodeDecodeError when executing google image download
How to Delete with SQLAlchemy?
How to output additional information when logging with python's logging module
How to not escape Japanese when dealing with json in python
How to deal with "You have multiple authentication backends configured ..." (Django)
How to display formulas in latex when using sympy (> = 1.4) in Google Colaboratory
How to deal with errors when installing whitenoise and deploying to Heroku
Here's a brief summary of how to get started with Django
How to pass arguments using an instance with systemd's systemctl command
How to deal with errors when installing Python and pip with choco
Unable to bind to interface error when using apollo federation with gqlgen
When you want to send an object with requests using flask
How to install python using anaconda
How to cancel RT with tweepy
Steps to develop Django with VSCode
Python: How to use async with
[Django] How to test Form [TDD]
How to deal with imbalanced data
How to install python-pip with ubuntu20.04LTS
Common html to rent with Django
How to deal with imbalanced data