From 997dccbf40546864d1a16bac155d07d7dcca0193 Mon Sep 17 00:00:00 2001 From: changeling Date: Sun, 26 May 2019 14:59:11 -0500 Subject: [PATCH] Created CORS/CSRF (markdown) --- CORS-CSRF.md | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 CORS-CSRF.md diff --git a/CORS-CSRF.md b/CORS-CSRF.md new file mode 100644 index 0000000..d114d6d --- /dev/null +++ b/CORS-CSRF.md @@ -0,0 +1,52 @@ +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](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)) + +[Mozilla.org CORS Page](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) + +[MixMax CSRF Page](https://engineering.mixmax.com/blog/modern-csrf) + +[Good discussion of the issues on StackOverflow](https://stackoverflow.com/questions/19793695/does-a-proper-cors-setup-prevent-xsrf)