1 CORS CSRF
changeling edited this page 2019-05-26 14:59:11 -05:00

One of the relatively common pain-points during django development, when connecting a front-end app to your backend, is the issue of Cross-Origin Resource Sharing (CORS) and/or Cross-Site Request Forgery (CSRF) preventing access. Here's a quick way to open up the door, as it were, between the two.

NOTE: We stress that this recommended for development only. When you decide to deploy your app, be sure to read up and understand the implications of CSRF and CORS to the security of your apps. See links at the bottom of this page for some discussion of what this is all about.

OK, so with that out of the way, here's a quick recipe for opening your backend up for specified external access. We're going to assume both resources exist on the same machine, using different ports.

First off, be sure you've installed django-cors-headers into your virtual environment (You're definitely working in a virtual environment, right? Right?):

pip install django-cors-headers

Next, add the following to your django settings.py:

INSTALLED_APPS += [
    'corsheaders',
]

(Or better, add the corsheader line to your existing INSTALLED_APPS. Same advice applies to the following MIDDLEWARE entry.)

MIDDLEWARE += [
    'corsheaders.middleware.CorsMiddleware',
]

and finally:

CORS_ORIGIN_WHITELIST = [
    'http://localhost:3000',
    'https://localhost:3000',
    'http://127.0.0.1:3000',
    'https://127.0.0.1:3000',
    ]

CORS_ALLOW_CREDENTIALS = True

NOTE: You may need to adjust the entries in CORS_ORIGIN_WHITELIST for your own context. Port 3000 is the common default for React applications.

Once you have these in place, you'll no longer need to exempt urls within your django for such things as graphiql using csrf_exempt(), but keep in mind the above (and below) security concerns when (if) you deploy.

CORS and CSRF further reading:

OWASP CSRF Page

Mozilla.org CORS Page

MixMax CSRF Page

Good discussion of the issues on StackOverflow