Card 07/ 10
CORS: Which Websites May Call Your API From a Browser
A browser blocks a page from reading another site's response unless that site's headers allow it.
Browsers apply the same-origin policy: script on a page from one origin, a scheme, host and port, may send requests to another origin but may not read the responses. CORS, Cross-Origin Resource Sharing, is how an API relaxes that for chosen websites, through response headers naming which origins may read its responses. For requests that could change data, the browser first asks permission with a preflight, an OPTIONS request.
What goes wrong. An API that answers every request with its Origin header copied into Access-Control-Allow-Origin, and Access-Control-Allow-Credentials: true, lets any website a user visits read the API's responses with that user's cookies.
A request that shows it. A request with Origin: https://evil.example that comes back with Access-Control-Allow-Origin: https://evil.example and credentials allowed.
The fix. Keep an allow-list of the origins that need access and echo the Origin only when it is on the list; add Vary: Origin so caches keep the answers apart. The wildcard * is fine for public data without credentials, and browsers refuse it when credentials are sent. Allow only the methods and headers the front end uses.
How to test. Send requests with an unlisted origin and a null origin, and check no Access-Control-Allow-Origin comes back for them.
So list the websites that may read the API from a browser, and never reflect whatever origin arrives.
← → move through sections and cards