[Fixed]-Django CSRF when backend and frontend are separated


This post is quite old but for people who still wander here:
For client-server setups, such as native desktop and mobile clients (and separate front end like the OP’s case), it is best to use Django Rest Framework’s Token Authentication. Link


If you look at the CRSF token source: you can see that all the csrf_middleware does it check the cookie against the post value. You just need to get the post value back to your server since the cookie should of already been set though ajax. If you look at the template tag source you can see that it is just taking the variable out of the context. Either stick it in your response by pulling it out of the context if it is available or calling the context processor directly. Now you just need to send it back as the POST variable crsf_token.


Lets say, frontend has the domain frontend.example.com, and backend domain backend.example.com. (If you are something like Django rest framework)
If you can use there are two ways you can enable security layer i.e.,. CSRF Protection or CORS


pip install django-cors-headers

and then configuring this to INSTALLED_APPS, MIDDLEWARE_CLASSES and add the frontend domain to CORS_ORIGIN_WHITELIST.


CORS will block any http request arising from any domains other than frontend.example.com


CSRF_COOKIE_DOMAIN = ".mydomain.com"

and if you are using an Angular App, do like below,

$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$httpProvider.defaults.withCredentials = true;

and then add headers while make a http request.

headers : {
    "x-csrftoken" : $cookies.csrftoken

Leave a comment