CORS Is Not Access Control: What the Browser Actually Enforces

CORS is one of the most misunderstood mechanisms on the web, and the misunderstanding has a consistent shape: developers treat it as a server-side security feature — a firewall that decides who can call the API. It isn’t. CORS is a browser-enforced mechanism for relaxing the same-origin policy, and its enforcement applies to exactly one party: the browser. A curl request, a Python script, or any non-browser client ignores CORS headers entirely and hits your API regardless of what you configure.

Getting this mental model right matters, because it determines where you place your real defenses. In this post we’ll walk through what the browser actually enforces, why some requests trigger a preflight and others don’t, how the credential rules work, and the configurations that quietly create vulnerabilities — including one that turns a misunderstanding of CORS into an account-compromise vector.

Start With the Same-Origin Policy

The browser’s default stance is strict: JavaScript loaded from one origin may not read responses from another. An origin is the triple of scheme, host, and port — https://app.example.com and https://api.example.com are different origins, as are http://localhost:3000 and http://localhost:8080. Without this policy, any page you visit could silently fetch your webmail inbox or your bank session (authenticated by ambient cookies) and exfiltrate the contents to the attacker.

But legitimate cross-origin reads are also constant in modern development: a frontend on one domain calling an API on another, a marketing site fetching pricing from a service, a local dev server talking to a staging backend. CORS is the negotiated escape hatch. The server declares, via response headers, which origins the browser may allow to read its responses. The browser enforces the declaration. That’s the entire contract.

Two consequences follow immediately. First, “fixing CORS errors” by adding headers only matters to browsers — your mobile app, CLI, and server-to-service calls were never subject to it. Second, CORS headers protect nothing on their own. If your API serves private data to anyone who asks without authenticating, CORS changes nothing about who can get it; it only changes what a browser-based attacker’s JavaScript can read.

Simple Requests vs Preflighted Requests

The browser sorts cross-origin requests into two buckets. “Simple” requests — roughly, GET, HEAD, or POST with only safelisted headers (Accept, Accept-Language, Content-Language, and Content-Type limited to text/plain, application/x-www-form-urlencoded, or multipart/form-data) — may be sent immediately. The browser delivers the request to the server, then inspects the response: if the appropriate Access-Control-Allow-Origin header matches the requesting origin, the JavaScript gets to read it. Otherwise the response is delivered to the network layer but hidden from the script.

Everything else — PUT, DELETE, PATCH, or anything carrying an Authorization header or a Content-Type: application/json body — gets a preflight. Before sending the real request, the browser sends an OPTIONS request describing what it intends to do:

OPTIONS /api/orders HTTP/1.1
Host: api.example.com
Origin: https://app.example.com
Access-Control-Request-Method: DELETE
Access-Control-Request-Headers: authorization

The server must answer with permission, and only then does the browser send the actual request:

HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Max-Age: 7200
Vary: Origin

This explains the most common confusion in API development: your frontend sends a DELETE and the server log shows a mysterious OPTIONS first. It also explains why adding a custom header suddenly “breaks” a previously working request — you moved it into the preflighted bucket, and the server never answered OPTIONS.

The preflight result is cacheable via Access-Control-Max-Age, and the values browsers actually honor are worth knowing: per MDN, Chromium caps it at two hours (7200 seconds), Firefox caps it at 24 hours, and the specification default when the header is absent is five seconds. Five seconds is why every request seems to trigger a fresh OPTIONS during development — send an explicit Max-Age and watch the preflights disappear.

Credentials: Where the Real Rules Live

Cookies and tokens sent by the browser itself — not attached by your JavaScript — are “credentials” in CORS terminology. When a fetch is made with credentials: 'include', the rules tighten: the server must echo the exact origin in Access-Control-Allow-Origin (the wildcard * is rejected), and must explicitly send Access-Control-Allow-Credentials: true. Miss either and the browser blocks the read even though the request itself went through.

A minimal, correct middleware in Go looks like this:

func CORS(allowed map[string]struct{}) func(http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            origin := r.Header.Get("Origin")
            if origin == "" {
                next.ServeHTTP(w, r) // same-origin or non-browser; CORS is irrelevant
                return
            }

            if _, ok := allowed[origin]; ok {
                h := w.Header()
                h.Add("Vary", "Origin") // caches must not share this response
                h.Set("Access-Control-Allow-Origin", origin)

                if r.Method == http.MethodOptions &&
                    r.Header.Get("Access-Control-Request-Method") != "" {
                    h.Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
                    h.Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
                    h.Set("Access-Control-Allow-Credentials", "true")
                    h.Set("Access-Control-Max-Age", "7200")
                    w.WriteHeader(http.StatusNoContent)
                    return
                }
            }
            next.ServeHTTP(w, r)
        })
    }
}

Note the Vary: Origin header. Because the response now differs depending on which origin asked, any CDN or proxy cache in front of the API must treat each origin as a distinct cache key. Omit it and you can serve one origin’s authorization to another — a real and recurring production incident class.

The Configuration That Becomes a Vulnerability

The credential rules exist because of an attacker pattern: a malicious page wants to read data from your API using the victim’s ambient cookie. Same-origin policy stops it; a permissive CORS misconfiguration un-stops it. The dangerous pattern is reflecting whatever Origin header arrives while allowing credentials:

// DANGEROUS — never do this
origin := r.Header.Get("Origin")
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")

With that code, an attacker hosts evil.example, tricks a logged-in user into visiting, and the page runs fetch('https://api.example.com/me', {credentials: 'include'}). The victim’s session cookie rides along, the API echoes https://evil.example as allowed, and the attacker’s JavaScript reads the response — the user’s profile, tokens, or whatever the endpoint returns. The same-origin policy, the thing you assumed was protecting the API, has been switched off by the API itself.

Wildcard subdomain matching has the same exposure. If you allow any origin matching *.example.com, ask what happens when someone can host content on a subdomain they control — a collaboration feature, a customer sandbox, a forgotten test environment. Subdomain takeover plus permissive origin matching reproduces the attack above. Allow-list exact origins you actually operate.

CORS Guards Reads; Auth Guards Everything

The subtlest point is what CORS does not do: it does not prevent requests from reaching your server. Even a fully blocked cross-origin POST still executes — the browser just hides the response. This is exactly the boundary between CORS and CSRF. CSRF defenses (SameSite cookies, anti-forgery tokens) exist because a state-changing request from an attacker’s page goes through whether or not CORS allows the response to be read. If you’re relying on CORS headers as your CSRF protection, you’re relying on a mechanism the attacker doesn’t need to bypass — they only needed the write, not the read.

So the division of labor is: CORS controls what cross-origin JavaScript can read in a browser; your server-side authentication and authorization control what any client can do. Every endpoint must enforce auth on its own merits, because non-browser clients never engage with CORS at all.

Wrapping Up

CORS is a delegation of trust from the browser to the server: the browser asks the server which origins it consents to, then enforces the answer — against the browser’s own scripts only. Configure it by allow-listing exact origins, echo the origin with Vary: Origin, set a real Access-Control-Max-Age to cut preflight noise, and treat credential mode as a privilege granted only to origins you operate end to end. And keep authentication where it belongs: verified on every request, regardless of what the Origin header says.

Leave a Reply

Your email address will not be published. Required fields are marked *