A Django REST backend and a SPA frontend, each on a different domain. According to the documentation, the frontend is supposed to get the token from a cookie. However it cannot access the cookie because it’s on a different domain and the browser does not allow this.
I would like to add the token to a custom header (by Django) instead of passing it in a cookie.
Is there a way to do this?
This would be an extremely bad idea - you might as well completely disable all CSRF protection if you go this route.
I don’t have a platform handy where I can test this, but my understanding is that your JavaScript can do an initial GET on a url that would get the cookie, and then submit that cookie on subsequent POSTs.
You might need to add your SPA host to the CSRF_TRUSTED_ORIGINS setting. Another option may be to set the CSRF_COOKIE_DOMAIN.
I suggest you review the docs at How to use Django’s CSRF protection | Django documentation | Django along with the set of CSRF_
related settings at Settings | Django documentation | Django to find the best solution for you that isn’t going to compromise the security of your site for your users.
No it is not, because the browser’s standard Same-origin policy is to not allow “foreign JavaScript” to access cookies from a response. In this specific case, that foreign JavaScript has access to the HTML but not those cookies.