mirror of
https://github.com/graphql-python/graphene-django.git
synced 2024-11-22 17:47:12 +03:00
Created CORS/CSRF (markdown)
parent
70a000d6cd
commit
997dccbf40
52
CORS-CSRF.md
Normal file
52
CORS-CSRF.md
Normal file
|
@ -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)
|
Loading…
Reference in New Issue
Block a user