CORS Lets a Server Relax the Same-Origin Policy, It Does Not Protect the Server

In progress AppSec

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

  1. A page on https://app.example calls fetch("https://api.example/items").
  2. For anything beyond a simple request (custom headers, JSON body, PUT/DELETE), the browser first sends a preflight OPTIONS request asking which origins, methods and headers are allowed.
  3. 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
  1. 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 with Access-Control-Allow-Credentials: true).
  • Never reflect the request's Origin header back unchecked: that allows every site, including an attacker's, to read authenticated responses.
  • Most frameworks have middleware for it: FastAPI's CORSMiddleware with allow_origins=[...], django-cors-headers for Django.

References

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 Origin header 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.