A developer hits a frustrating error in the browser console: “blocked by CORS policy”. After an hour of searching, they paste a snippet that reflects whatever Origin header arrives and sets Access-Control-Allow-Credentials: true. The error disappears, the feature ships, and every logged-in user’s data is now readable by any website they visit. This is one of the most common ways a CORS “fix” turns into a vulnerability, and it happens because the mechanism is widely misunderstood.

This article explains what the browser enforces, what it does not, how the typical misconfigurations look, and how to test and fix them. Everything here is meant for systems you own or are explicitly authorized to assess.

What CORS Is, and What It Is Not

Browsers apply the same-origin policy: a script running on https://app.example.com cannot read responses from https://api.example.org. An origin is the triple of scheme, host and port. Two URLs that differ in any of the three are different origins.

Cross-Origin Resource Sharing (CORS) is a controlled relaxation of that policy. The server opts in by sending response headers that tell the browser which foreign origins may read its responses.

Three misconceptions cause most of the trouble:

  • CORS is not access control for your server. It restricts what a browser lets a page read. curl, a script, or a malicious server can call your API regardless of CORS headers.
  • CORS does not stop requests from being sent. For “simple” requests (for example a form-style POST), the request reaches your server and is processed. CORS only prevents the calling page from reading the response. State-changing endpoints still need CSRF protection.
  • CORS is not a defense against an attacker who is not using a victim’s browser. Its threat model is a malicious web page driving a victim’s authenticated browser session.

Keeping this model in mind makes every misconfiguration easier to reason about: the risk exists when a victim’s browser carries credentials (cookies, HTTP auth, client certificates) to your API and your headers allow a hostile origin to read the answer.

The Headers That Matter

The core response headers are:

HeaderPurpose
Access-Control-Allow-OriginWhich origin may read the response (one origin, or *)
Access-Control-Allow-CredentialsWhether credentialed requests may be read (true only)
Access-Control-Allow-MethodsMethods allowed in a preflighted request
Access-Control-Allow-HeadersRequest headers allowed in a preflighted request
Access-Control-Max-AgeHow long the browser may cache a preflight result
Vary: OriginTells caches the response depends on the request Origin

Two rules are enforced by the browser and are worth memorizing:

  1. Access-Control-Allow-Origin: * cannot be combined with credentials. If the request includes cookies and the response says *, the browser refuses to expose the response to the page.
  2. Access-Control-Allow-Origin accepts exactly one origin (or *, or null). A comma-separated list is invalid and will be rejected.

Because of rule 2, servers that want to support several origins must pick the value dynamically from an allowlist. That dynamic step is where most bugs are introduced.

Preflight Requests

Requests that are not “simple” trigger a preflight: the browser first sends an OPTIONS request asking permission. A request is preflighted when it uses a method other than GET, HEAD or POST, carries custom headers such as Authorization or X-Api-Key, or uses a content type such as application/json.

OPTIONS /v1/account HTTP/1.1
Host: api.example.org
Origin: https://app.example.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: content-type, authorization

A correct answer from the server:

HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, PUT
Access-Control-Allow-Headers: content-type, authorization
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 600
Vary: Origin

Preflight is a convenience for the browser, not a security boundary. A server must still authenticate and authorize every actual request. A common mistake is to build authentication only into the main handler and let OPTIONS fall through to a router that returns a 401 with no CORS headers, which breaks legitimate clients and encourages hasty “fixes”.

Misconfiguration 1: Reflecting Any Origin

The most dangerous pattern copies the request’s Origin header straight into the response:

// VULNERABLE: reflects any origin and allows credentials
app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", req.headers.origin);
  res.setHeader("Access-Control-Allow-Credentials", "true");
  next();
});

With this code, a page on https://evil.example.net can run fetch("https://api.example.org/v1/account", { credentials: "include" }) in a visitor’s browser and read the JSON. If the visitor is logged in to the API, the attacker’s page receives their personal data, API tokens embedded in responses, or CSRF tokens that unlock further actions.

Whether the browser sends the cookie also depends on the cookie’s SameSite attribute. Cookies marked SameSite=Lax or Strict are not sent on cross-site fetch calls, which limits exposure, but you should not rely on that alone: sites on a sibling subdomain are same-site, and older cookies or legacy flows may have SameSite=None. The cookie attributes are covered in Session Management and Cookie Security.

The fix: a strict allowlist with exact matching

const ALLOWED = new Set([
  "https://app.example.com",
  "https://admin.example.com",
]);

app.use((req, res, next) => {
  const origin = req.headers.origin;
  res.append("Vary", "Origin");
  if (origin && ALLOWED.has(origin)) {
    res.setHeader("Access-Control-Allow-Origin", origin);
    res.setHeader("Access-Control-Allow-Credentials", "true");
  }
  next();
});

Use exact string comparison against full origins, including scheme. Do not use regular expressions unless you anchor them and escape every dot, and do not use startsWith or endsWith.

Misconfiguration 2: Weak Origin Validation

Teams that realize they should validate often write checks that are almost, but not quite, correct:

// VULNERABLE examples of broken validation
origin.endsWith("example.com");        // matches https://evilexample.com
origin.startsWith("https://example.com"); // matches https://example.com.evil.example.net
origin.includes("example.com");        // matches both of the above
/example.com$/.test(origin);           // unescaped dot, unanchored start

Each of these accepts a domain an attacker can register. The fix is not a cleverer regex; it is a lookup in a fixed set. If you must allow many tenant subdomains, parse the origin with a URL parser, require https:, and compare the hostname against a pattern such as “one DNS label followed by .example.com”, with the label restricted to [a-z0-9-].

Even a correct wildcard-subdomain policy carries a trade-off: any subdomain that suffers an XSS flaw or a subdomain takeover becomes a valid origin for reading authenticated data. Prefer an explicit list for credentialed APIs.

Misconfiguration 3: Trusting the null Origin

Browsers send Origin: null in several situations: sandboxed iframes, file: pages, some redirects and data URLs. Some servers add null to the allowlist so that local development works, then forget to remove it.

Access-Control-Allow-Origin: null
Access-Control-Allow-Credentials: true

An attacker can produce the null origin on demand from a sandboxed iframe on any page they control, so allowing it with credentials is equivalent to allowing everyone. Never allow null outside of a throwaway local environment, and keep development allowlists out of production configuration.

Misconfiguration 4: Wildcards and Internal Networks

Access-Control-Allow-Origin: * on a public, unauthenticated API (a font CDN, open data, public documentation) is fine and often correct. The risk appears in two other places.

First, wildcard on an endpoint that authenticates by something other than cookies but still exposes sensitive data based on network position. An intranet application that trusts requests coming from the corporate network, and answers with *, can be read by any web page a staff member opens, because the staff member’s browser is on the corporate network. The page’s JavaScript becomes a proxy into the internal network. Requests to private address ranges are increasingly restricted by browsers, but you should not depend on that.

Second, wildcard on development or staging services that sit behind a VPN and hold copies of production data. Treat these like production.

Misconfiguration 5: Missing Vary and Cache Poisoning

If a response’s Access-Control-Allow-Origin depends on the request Origin, the response must carry Vary: Origin. Without it, a shared cache or CDN may store the response generated for https://app.example.com and serve it to a request from another origin, or the reverse. Either the legitimate application starts failing intermittently, or a cached permissive header is delivered to origins that should not have it.

location /v1/ {
    add_header Vary Origin always;
    proxy_pass http://backend;
}

If you build the header in application code, set Vary there too. Check with curl -I through your CDN, not just against the origin server.

Testing Your Own API

On systems you own or have written permission to test, a handful of requests reveal most problems. Replace the hostnames with your own.

# 1. Does the server reflect arbitrary origins?
curl -s -I https://api.example.org/v1/account \
  -H "Origin: https://not-allowed.example.net" | grep -i "access-control"

# 2. Does a lookalike suffix pass validation?
curl -s -I https://api.example.org/v1/account \
  -H "Origin: https://evilexample.com" | grep -i "access-control"

# 3. Is the null origin accepted?
curl -s -I https://api.example.org/v1/account \
  -H "Origin: null" | grep -i "access-control"

# 4. How does a preflight behave?
curl -s -i -X OPTIONS https://api.example.org/v1/account \
  -H "Origin: https://not-allowed.example.net" \
  -H "Access-Control-Request-Method: PUT" | head -20

A healthy API returns no Access-Control-Allow-Origin header at all for origins outside the allowlist. Any response that echoes a hostile origin, especially together with Access-Control-Allow-Credentials: true, is a finding. Also test a path prefix variant and an uppercase scheme or host, since normalization differences between the proxy and the application sometimes let a mismatched value through.

Remember that the response to these curl calls proves what the server says; whether a browser would expose the response also depends on the cookie attributes and on the endpoint requiring credentials. When you write up a finding, demonstrate the impact with your own test account and a page you control, never with other people’s data.

Fixing It Properly

A defensible CORS design is short:

  1. Decide which endpoints need cross-origin access at all. Many APIs are consumed only by a front end on the same origin, behind a reverse proxy. In that case send no CORS headers.
  2. Use an exact allowlist of full origins, loaded from configuration, with different lists per environment.
  3. Only send Allow-Credentials: true where cookies are really needed. Token-based APIs that use an Authorization header set in JavaScript do not need it, and avoiding it removes the ambient-credential risk.
  4. Always send Vary: Origin when the value is dynamic.
  5. Keep Allow-Methods and Allow-Headers minimal, and keep Max-Age modest so policy changes take effect.
  6. Authenticate and authorize every request on the server, and protect state-changing routes against CSRF independently of CORS. Broken object-level checks remain a separate problem, discussed in IDOR and Broken Access Control.

If your API sits behind a reverse proxy, centralizing the policy there keeps it consistent; see Reverse Proxy Hardening With Traefik and Nginx for patterns. Traefik, for example, exposes an explicit allowlist through its headers middleware:

http:
  middlewares:
    api-cors:
      headers:
        accessControlAllowOriginList:
          - "https://app.example.com"
        accessControlAllowCredentials: true
        accessControlAllowMethods: ["GET", "PUT"]
        accessControlAllowHeaders: ["content-type", "authorization"]
        addVaryHeader: true

Common Mistakes Checklist

  • Treating a CORS error as a server bug to silence, instead of asking which origin should be allowed.
  • Reflecting the Origin header or using a permissive regular expression.
  • Allowing null for convenience.
  • Combining a dynamic origin with a CDN and no Vary: Origin.
  • Assuming CORS protects the API from non-browser clients.
  • Forgetting that a sibling subdomain with an XSS bug can read data from an API that trusts the whole domain.
  • Leaving permissive development settings in production images.

Key Takeaways

  • CORS controls what a browser lets a page read; it does not authenticate callers and does not stop the request from reaching your server.
  • Never reflect the Origin header, and never combine a permissive origin policy with Access-Control-Allow-Credentials: true.
  • Validate origins with an exact allowlist of full origins; substring, suffix and prefix checks are bypassable with attacker-registered domains.
  • Do not allow the null origin in production, and always send Vary: Origin when the header is dynamic.
  • If an API does not need cross-origin access, send no CORS headers at all.
  • Test with crafted Origin headers on systems you own or are authorized to assess, and fix findings at the root rather than loosening headers until errors disappear.