CORS Lets a Server Relax the Same-Origin Policy, It Does Not Protect the Server
Browsers enforce the same-origin policy: a script on https://app.example may send requests elsewhere but may not read responses from another origin (a different scheme, host or port). Cross-Origin Resource Sharing (CORS) is how a server opts out, with response headers that tell the browser which other origins may read its responses. It's a browser rule, so it doesn't stop curl, scripts or servers from calling an API: authentication and authorization still do that.
How a Cross-Origin Call Works
- A page on
https://app.examplecallsfetch("https://api.example/items"). - For anything beyond a simple request (custom headers, JSON body,
PUT/DELETE), the browser first sends a preflightOPTIONSrequest asking which origins, methods and headers are allowed. - The API answers with headers such as:
Access-Control-Allow-Origin: https://app.example
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: Content-Type, Authorization
- If the page's origin is allowed, the browser sends the real request and lets the script read the response; otherwise the script gets a CORS error.
Configuring It Safely
- List the exact origins that need access; avoid
*for anything that uses credentials (browsers refuse*together withAccess-Control-Allow-Credentials: true). - Never reflect the request's
Originheader back unchecked: that allows every site, including an attacker's, to read authenticated responses. - Most frameworks have middleware for it: FastAPI's
CORSMiddlewarewithallow_origins=[...],django-cors-headersfor Django.
References
- Web Application and Django Security MOC - hub for web security notes.
- A REST API Exposes Resources at Endpoints and Acts on Them with HTTP Methods - the APIs CORS headers apply to.
- MDN: Cross-Origin Resource Sharing (CORS) - preflights and headers.
- FastAPI documentation: CORS -
CORSMiddlewaresettings.
Review cards
Flashcard Why doesn't CORS protect an API from unwanted callers?
It's a browser rule: it only decides which other origins' scripts may read the responses. curl, scripts and servers call the endpoint anyway, so authentication and authorization must protect the data.
Flashcard What happens with `Access-Control-Allow-Origin: *` plus `Access-Control-Allow-Credentials: true`?
Browsers refuse the combination, and the script gets a CORS error for credentialed requests. List the exact origins instead.
Quiz Which CORS setup is safe for an API that uses cookies?
-
Access-Control-Allow-Origin: * - An explicit list of the origins that need access
- Reflecting the request's
Originheader back - No CORS headers, and rely on that for access control
Reflecting Origin lets every site, an attacker's included, read authenticated responses, and * is refused with credentials. Missing headers only stop browsers, not callers.