← Study Notes Security


Security

CORS

Cross-Origin Resource Sharing is the browser policy governing which other origins may read responses from your API, relaxing the same-origin policy via Access-Control headers. It is a browser protection, not server security — a permissive wildcard combined with credentials is a common and dangerous misconfiguration. It does not restrict non-browser clients at all.


Purpose

CORS (Cross-Origin Resource Sharing) is the browser mechanism that relaxes the same-origin policy: by default, a page on one origin cannot read responses from another, and Access-Control-* headers let a server opt specific origins in. It exists so cross-origin APIs are possible without letting every website read every other site's data through the visitor's browser.

When to Use It

You configure it whenever a frontend on one origin calls an API on another — app.example.com calling api.example.com, or third parties consuming your public API from the browser. Preflight OPTIONS requests are the browser asking permission before non-simple requests.

Trade-offs

The critical misunderstanding: CORS protects browser users, not your server — curl and backend clients ignore it entirely, so it is never an access-control mechanism. The dangerous misconfiguration is reflecting any origin while also allowing credentials, which hands authenticated data to arbitrary sites.

Implementation

Allow-list exact origins (never * together with Access-Control-Allow-Credentials), limit allowed methods and headers, and set a sensible preflight cache (Access-Control-Max-Age). Keep real authorization on the server; treat CORS purely as a browser-exposure decision.