I'm creating a web app with a React frontend and Django REST Framework backend. Due to some circumstances, I have to develop the React frontend locally while the backend server is at a remote location.
The backend server requires me to use the CSRF token for every POST after login, and I'm supposed to be able to retrieve the csrftoken from the cookie that the backend sends. I've verified that the cookie does get sent over the network and is included in the response headers in the form of:
Set-Cookie:csrftoken=******; Domain=localhost; expires=Sat, 09-Dec-2017 18:50:56 GMT; Max-Age=31449600; Path=/
Unfortunately, since the the domain of the frontend (localhost) and the domain of the backend (remote.com) are different, the browser ignores this set-cookie header, and I am unable to access it. If I enable CORS_ALLOW_CREDENTIALS (and specify localhost as an accepted domain), and use withCredentials from the frontend, then the cookie does get set but under the remote.com cookie store, in which case I am still unable to access it due to same origin policy for cookie access.
How do I get access to this csrftoken cookie? Or should I have Django send the csrftoken as part of the body somewhere? If so, what would be the simplest way of doing that?
Here are the relevant parts of my settings.py which have CORS and CSRF enabled. Note that I am using SessionBasedAuthentication for this.
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
...
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
]
...
}
# CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
'localhost:8080',
)
CORS_ALLOW_CREDENTIALS = True
I am using django-corsheaders for CORS support and have included corsheaders in my INSTALLED_APPS. The React frontend uses superagent to make AJAX queries to the backend.
Thank you in advance.
EDIT: I have also considered using JWT instead of session-based authentication, but for the browser, I would likely store the JWT in a cookie, in which case I need CSRF protection anyway, leading back to this problem.
EDIT: This post has a very similar problem, and has a great answer, but I didn't understand how you would get access to the cookie from a different origin.