The careful parent
Your browser fetches things for every page you open, and it carries your cookies, so websites recognise you. That's a problem if a stranger's page asks it to fetch your bank details.
So the browser acts like a careful parent. It will happily fetch things, but it won't hand the answer to a page from somewhere else unless it has permission.
The same-origin policy
An origin is scheme + host + port: https://shop.com and https://api.shop.com are different origins, and
so are http:// and https:// versions of the same host.
By default, script on one origin can send requests to another, but can't read the responses. This same-origin policy stops a malicious page from reading your data on other sites, even though the browser attaches your cookies for those sites.
The permission slip
The parent labels every request with who's asking. If the office replies with a permission slip naming that page, the parent hands the answer over. No slip, no answer.
Opting in with headers
Cross-Origin Resource Sharing lets a server relax the policy. The browser adds an Origin header and the
server answers with:
| Header | Meaning |
|---|---|
Access-Control-Allow-Origin | Which origin may read this (https://shop.com, or * for anyone) |
Access-Control-Allow-Credentials | Whether cookies may be included; can't be combined with * |
Access-Control-Expose-Headers | Response headers the script may see |
CORS is enforced by browsers. It protects users, not your server: curl or another server can still call your API, so you still need real authentication.
Asking first
For notes that want to change things, the parent rings the office before sending anything: "would you accept this kind of request from this page?" Only after a yes does the real request go.
Preflight requests
A request is "simple" only if it's a GET, HEAD or POST with basic headers and a form-style content type.
Anything else (a PUT or DELETE, a JSON body, an Authorization header) triggers an OPTIONS preflight
first. The server must answer with Access-Control-Allow-Methods and Access-Control-Allow-Headers, and
Access-Control-Max-Age lets the browser cache that answer.
If a CORS request fails, look at the preflight in the browser's network tab: the usual cause is a server that
doesn't handle OPTIONS, or a missing allowed header.
In Spring: @CrossOrigin(origins = "https://shop.com") on a controller, or a global
CorsConfigurationSource bean, which Spring Security picks up with http.cors(...).
Don't reflect blindly: echoing back whatever Origin arrives, with credentials allowed, is the same as
turning the policy off.