Course · Applications · 29 / 69
CORS explained: what it allows, what it does not protect, and the misconfigurations to look for
How the browser’s same-origin policy and CORS headers decide whether a page on one origin can read a response from another, why CORS is not authentication, and the reflected-origin and null-origin mistakes that expose APIs.
Diagram
A cross-origin read
JavaScript on app.example.org calls api.example.org.
# Page # JavaScript on app.example.org calls api.example.org.
The example on the open step is one illustration, or the fix you can paste into an application you own.
What this page is made of
A short map of the pieces. Each piece says what fails, who is affected, what you would notice, and what you change.
Reflected origin with credentials
- What fails
- Echoing any Origin back with Allow-Credentials lets every website read authenticated responses.
- Who is affected
- Every signed-in user who visits a hostile page.
- What you would notice
- Access-Control-Allow-Origin matching whatever Origin you send, plus Allow-Credentials: true.
- What you change
- Compare against an exact allow-list.
null and suffix matches
- What fails
- Allowing the null origin or matching on endsWith lets sandboxed frames and lookalike domains in.
- Who is affected
- The same users.
- What you would notice
- Origin: null accepted, or evil-example.org accepted for example.org.
- What you change
- Exact string comparison only.
CORS is not access control
- What fails
- CORS controls browsers reading responses; curl and servers ignore it.
- Who is affected
- Anyone relying on CORS to protect an API.
- What you would notice
- An API without authentication because CORS is “restricted”.
- What you change
- Authenticate and authorize every API request.
Testing an API you own
Send requests with different Origin values and read the response headers. The only origins reflected should be the ones on your list.
$ for o in https://app.example.org https://evil.example https://app.example.org.evil.example null; do
printf "%-40s " "$o"; curl -s -o /dev/null -D - -H "Origin: $o" https://api.example.org/v1/me | grep -i "access-control-allow-origin" || echo "(none)"
done
https://app.example.org access-control-allow-origin: https://app.example.org
https://evil.example (none)
https://app.example.org.evil.example (none)
null (none)Caching
When the allowed origin varies per request, send Vary: Origin so caches do not serve one origin’s CORS headers to another.
Check yourself
Recognition and the fix. Nothing here is a procedure.
An API echoes any Origin and sets Allow-Credentials: true. What is the impact?
Sibling techniques
Pages at the same depth, plus a lab and a glossary card for this one.