02 CORS Demo
Intro
The idea behind CORS is to guard your API against unauthorized requests from third party sites. For example, imagine you're developing an API for a bank. You would want to prevent an evil website from embedding some javascript on their site that calls the bank's API using the customer's session credentials while they're logged into the bank from a different tab.
To avoid this situation, all browsers respect a special
access-control-allow-origin
header that your API sends back in responses.
This provides a list of origins whose javascript the browser should allow
to make requests to the API. Origins are defined as the combination of
protocol://domain:port
.
The API configures the access-control-allow-origin
header within
config/settings.py
as follows:
CORS_ALLOWED_ORIGINS = [
"http://127.0.0.1:8001", # Docs site
"http://mealpointsapp.localhost:8001", # CORS demo site
]
So, if you wanted to allow AJAX (i.e. javascript) requests from a React.js front-end hosted on a different origin than your API, you would need to add that to your project's settings.
Setup
Let's demo CORS with the local API. It will work if you're viewing this page
from a development mkdocs server running from an origin of
http://mealpointsapp.localhost:8001
...
- You're currently viewing this page from the origin:
thinking...
- Therefore, the API will thinking... your request.
Demo
Below is a form that'll transfer some "meal points" using a dummy endpoint in the API. Let's try it from two different origins. Open each of these links in different tabs and then click Transfer below:
http://mealpointsapp.localhost:8001/lab/02_cors_demo/
http://badguys.localhost:8001/lab/02_cors_demo/
Note
mealpointsapp.localhost
and badguys.localhost
are both addresses that
point back to your local machine; however, because they're different
domains each address represents a different origin.
Transfer "meal points"
If you submit the above for from an allowed origin, then you should get an alert:
But, if you submit it from a disallowed origin, then you'll get an error and should see something like below in your browser console: