Part 03 · The Language of the Web
CORS: Why Browsers Say No
Why a browser blocks some cross-origin calls, and how a server grants permission.
⏱ 1-2 hours · Station 35 of 153
It works in Postman, so why not in the browser?
You build an API at https://api.shop.com and a frontend at https://app.shop.com. Every request works in curl and Postman. Then the frontend calls it with fetch, and the console turns red:
Access to fetch at 'https://api.shop.com/cart' from origin 'https://app.shop.com'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present
on the requested resource.
Nothing is wrong with your API. curl and Postman are just programs sending bytes; they don't care who asked. The browser is different. It runs code from thousands of websites, and every one of them could try to use your logged-in cookies to read your bank, your email or your company dashboard. So the browser keeps a strict rule: a page may only read responses from its own origin, unless the other server says "yes, that page is allowed".
That "yes" is CORS, Cross-Origin Resource Sharing. It's a set of HTTP headers the server sends, and a set of rules the browser follows. Once you see that the server gives permission and the browser enforces it, the red console errors become easy to fix, and you'll stop "fixing" them in ways that open security holes.
The problem: the browser holds your keys
When you're logged in to bank.com, your browser holds its session cookie. Now you open evil.example in another tab. Its JavaScript can try:
fetch("https://bank.com/api/balance", { credentials: "include" })
The browser would attach your bank cookie automatically (lesson 6). If the page could then read the response, any website you visit could read your balance, your messages and your private data.
| Who sends the request | Has your cookies? | Who decides if the response can be read |
|---|---|---|
| curl, Postman, a backend service | no (only what you give it) | nobody, the program just reads it |
| A page on the same origin | yes | nobody, same origin is trusted |
| A page on another origin | yes, the browser attaches them | the server via CORS headers, enforced by the browser |
The same-origin policy is the default "no". CORS is the controlled way for a server to say "yes" to specific other origins.
Think of a school gate
A school gatekeeper lets parents pick up children. A stranger walks up and says "I'm here for Rafi".
- The gatekeeper doesn't decide on their own. They check the list the parents gave the school: who is allowed to collect this child.
- If the stranger is on the list, the child goes with them. If not, the child stays inside.
- The gatekeeper protects the child (your data in the response). It doesn't stop strangers from walking up to the gate and talking (the request still arrives).
The browser is the gatekeeper, the server writes the list (CORS headers), and the response is the child.
Where the analogy stops working. A gatekeeper stops the stranger before anything happens. For "simple" requests, the browser sends the request first and only hides the response afterwards. The server still runs the handler. That's why CORS is not protection for your server, only for your users' data.
The building blocks
- Origin = scheme + host + port.
https://app.shop.comandhttps://api.shop.comare different origins (different host). So arehttp://shop.comandhttps://shop.com(different scheme), andlocalhost:3000andlocalhost:8080(different port). The path doesn't matter. - The browser sends
Origin. On a cross-origin request, the browser addsOrigin: https://app.shop.com. The page can't fake it; JavaScript isn't allowed to set this header. - The server answers with
Access-Control-Allow-Origin. Either the exact origin (https://app.shop.com) or*(anyone). If it's missing or doesn't match, the browser blocks JavaScript from reading the response. - Simple requests go straight out. GET, HEAD or POST with only basic headers (no
Authorization, andContent-Typeonlytext/plain, form data or multipart) are sent immediately. These are the same requests an HTML form could always send, so CORS adds no new risk by allowing them out. - Everything else gets a preflight. PUT, DELETE, PATCH, a JSON
Content-Typeor anAuthorizationheader: the browser first sendsOPTIONSwithAccess-Control-Request-MethodandAccess-Control-Request-Headers. Only if the answer allows that origin, method and headers does the real request go out. - Preflight results are cached.
Access-Control-Max-Age: 600lets the browser skip the preflight for that URL for 10 minutes. Without it, every non-simple call costs an extra round trip. - Cookies need extra permission. With
credentials: "include", the server must reply with the exact origin (not*) andAccess-Control-Allow-Credentials: true. A wildcard with credentials is always rejected, so a public*API can never be read with a user's cookies. Vary: Origin. If the response changes with theOriginheader, say so, or a cache or CDN may give one origin's CORS headers to another.
A page on https://evil.example runs fetch('https://api.shop.com/cart', { credentials: 'include' }) with a simple GET. api.shop.com sends no CORS headers. What happens on the server?
Behind the scenes: a DELETE from another origin
The frontend deletes a cart item
Step 1/5 The page calls fetch
JavaScript on https://app.shop.com calls fetch('https://api.shop.com/cart/7', { method: 'DELETE', headers: { Authorization: 'Bearer t1' } }).
- origin
- https://app.shop.com
- method
- DELETE
The picture to keep in your head
CORS is a permission slip written by the server and checked by the browser.
- Server writes it:
Access-Control-Allow-Originand friends, per origin. - Browser checks it: before handing a response to JavaScript, and before sending risky requests (preflight).
- Non-browser clients ignore it: curl, mobile apps and other servers never look at the slip.
- It protects users' data, not your server: authentication, authorization and CSRF defences still have to live on the server.
Try it: will the browser allow it?
Allowed or blocked?
no CORS headers needed
Code from first principles
A small API server with a CORS policy (it trusts only https://app.shop.com, and /public is open to everyone without cookies), plus a tiny "browser" that follows the CORS rules: simple requests go straight out, others get a preflight, and the response is handed to the page only if the headers allow it. The server logs every request that reaches it, so you can see what CORS does and doesn't stop.
package main
import (
"bufio"
"fmt"
"io"
"net"
"strings"
)
const api = "https://api.shop.com" // the server's own origin
var allowed = map[string]bool{"https://app.shop.com": true}
var seen []string // every request that reached the server
type resp struct {
status int
headers map[string]string
body string
}
// parseHead reads a request or response head and returns its first line and lower-cased headers.
func parseHead(r *bufio.Reader) (string, map[string]string) {
first, _ := r.ReadString('\n')
h := map[string]string{}
for {
line, err := r.ReadString('\n')
if err != nil || line == "\r\n" {
break
}
k, v, _ := strings.Cut(strings.TrimRight(line, "\r\n"), ": ")
h[strings.ToLower(k)] = v
}
return strings.TrimSpace(first), h
}
// The API server and its CORS policy.
func handle(conn net.Conn) {
defer conn.Close()
line, h := parseHead(bufio.NewReader(conn))
parts := strings.Fields(line)
method, path := parts[0], parts[1]
seen = append(seen, method+" "+path)
origin := h["origin"]
out := map[string]string{}
status, body := 200, ""
switch {
case method == "OPTIONS": // preflight: say what's allowed, only to origins we trust
status = 204
if allowed[origin] {
out["Access-Control-Allow-Origin"] = origin
out["Access-Control-Allow-Methods"] = "GET, POST, DELETE"
out["Access-Control-Allow-Headers"] = "Authorization, Content-Type"
out["Access-Control-Max-Age"] = "600"
}
case path == "/public": // public data: any site may read it, but not with cookies
out["Access-Control-Allow-Origin"] = "*"
body = `{"news":"sale"}`
default:
if allowed[origin] {
out["Access-Control-Allow-Origin"] = origin
out["Access-Control-Allow-Credentials"] = "true"
}
if method == "DELETE" {
body = `{"deleted":7}`
} else {
body = `{"items":2}`
}
}
reason := map[int]string{200: "OK", 204: "No Content"}[status]
fmt.Fprintf(conn, "HTTP/1.1 %d %s\r\nContent-Length: %d\r\nVary: Origin\r\n", status, reason, len(body))
for _, k := range []string{"Access-Control-Allow-Origin", "Access-Control-Allow-Credentials",
"Access-Control-Allow-Methods", "Access-Control-Allow-Headers", "Access-Control-Max-Age"} {
if v, ok := out[k]; ok {
fmt.Fprintf(conn, "%s: %s\r\n", k, v)
}
}
fmt.Fprintf(conn, "Connection: close\r\n\r\n%s", body)
}
func send(method, path string, headers [][2]string) resp {
conn, _ := net.Dial("tcp", "127.0.0.1:8097")
defer conn.Close()
req := method + " " + path + " HTTP/1.1\r\nHost: api.shop.com\r\n"
for _, kv := range headers {
req += kv[0] + ": " + kv[1] + "\r\n"
}
io.WriteString(conn, req+"Connection: close\r\n\r\n")
r := bufio.NewReader(conn)
first, h := parseHead(r)
var status int
fmt.Sscanf(first, "HTTP/1.1 %d", &status)
body, _ := io.ReadAll(r)
return resp{status, h, string(body)}
}
// A tiny browser: it follows the CORS rules before letting the page's JavaScript see anything.
func fetch(page, method, path, auth string, cookies bool) string {
extra := ""
if cookies {
extra = " +cookies"
}
label := fmt.Sprintf("%s %s from %s%s", method, path, page, extra)
var hs [][2]string
if cookies {
hs = append(hs, [2]string{"Cookie", "session=abc"})
}
if auth != "" {
hs = append(hs, [2]string{"Authorization", auth})
}
if page == api { // same origin: no CORS check at all
r := send(method, path, hs)
return fmt.Sprintf("%s (same origin): %d, JS reads %s", label, r.status, r.body)
}
pre := ""
simple := (method == "GET" || method == "HEAD" || method == "POST") && auth == ""
if !simple { // ask permission first
p := send("OPTIONS", path, [][2]string{{"Origin", page},
{"Access-Control-Request-Method", method}, {"Access-Control-Request-Headers", "authorization"}})
ok := p.headers["access-control-allow-origin"] == page &&
strings.Contains(p.headers["access-control-allow-methods"], method) &&
strings.Contains(strings.ToLower(p.headers["access-control-allow-headers"]), "authorization")
if !ok {
return fmt.Sprintf("%s: preflight failed, %s never sent", label, method)
}
pre = "preflight ok, "
}
r := send(method, path, append([][2]string{{"Origin", page}}, hs...))
acao := r.headers["access-control-allow-origin"]
blocked := ""
switch {
case acao == "":
blocked = "no Access-Control-Allow-Origin"
case acao == "*" && cookies:
blocked = "wildcard * not allowed with cookies"
case acao != "*" && acao != page:
blocked = "origin does not match"
case cookies && r.headers["access-control-allow-credentials"] != "true":
blocked = "credentials not allowed"
}
if blocked != "" {
return fmt.Sprintf("%s: %s%d, blocked: %s", label, pre, r.status, blocked)
}
return fmt.Sprintf("%s: %s%d, JS reads %s", label, pre, r.status, r.body)
}
func main() {
ln, _ := net.Listen("tcp", "127.0.0.1:8097")
go func() {
for {
c, err := ln.Accept()
if err != nil {
return
}
handle(c)
}
}()
app, evil := "https://app.shop.com", "https://evil.example"
lines := []string{
fetch(api, "GET", "/cart", "", true),
fetch(app, "GET", "/cart", "", true),
fetch(evil, "GET", "/cart", "", true),
fetch(app, "DELETE", "/cart/7", "Bearer t1", false),
fetch(evil, "DELETE", "/cart/7", "Bearer t1", false),
fetch(evil, "GET", "/public", "", false),
fetch(app, "GET", "/public", "", true),
}
for i, l := range lines {
fmt.Printf("%d. %s\n", i+1, l)
}
fmt.Printf("server saw %d requests: %s\n", len(seen), strings.Join(seen, ", "))
}const net = require("net");
const api = "https://api.shop.com"; // the server's own origin
const allowed = new Set(["https://app.shop.com"]);
const seen = []; // every request that reached the server
// parseHead splits a request or response head into its first line and lower-cased headers.
function parseHead(text) {
const [first, ...lines] = text.split("\r\n");
const h = {};
for (const line of lines) {
const i = line.indexOf(": ");
if (i > 0) h[line.slice(0, i).toLowerCase()] = line.slice(i + 2);
}
return [first, h];
}
// The API server and its CORS policy.
function handle(conn, head) {
const [line, h] = parseHead(head);
const [method, path] = line.split(" ");
seen.push(method + " " + path);
const origin = h["origin"];
const out = {};
let status = 200, body = "";
if (method === "OPTIONS") { // preflight: say what's allowed, only to origins we trust
status = 204;
if (allowed.has(origin)) {
out["Access-Control-Allow-Origin"] = origin;
out["Access-Control-Allow-Methods"] = "GET, POST, DELETE";
out["Access-Control-Allow-Headers"] = "Authorization, Content-Type";
out["Access-Control-Max-Age"] = "600";
}
} else if (path === "/public") { // public data: any site may read it, but not with cookies
out["Access-Control-Allow-Origin"] = "*";
body = '{"news":"sale"}';
} else {
if (allowed.has(origin)) {
out["Access-Control-Allow-Origin"] = origin;
out["Access-Control-Allow-Credentials"] = "true";
}
body = method === "DELETE" ? '{"deleted":7}' : '{"items":2}';
}
const reason = { 200: "OK", 204: "No Content" }[status];
let res = `HTTP/1.1 ${status} ${reason}\r\nContent-Length: ${body.length}\r\nVary: Origin\r\n`;
for (const k of ["Access-Control-Allow-Origin", "Access-Control-Allow-Credentials",
"Access-Control-Allow-Methods", "Access-Control-Allow-Headers", "Access-Control-Max-Age"]) {
if (k in out) res += `${k}: ${out[k]}\r\n`;
}
conn.end(res + "Connection: close\r\n\r\n" + body);
}
function send(method, path, headers) {
return new Promise((resolve) => {
const conn = net.connect(8097, "127.0.0.1");
let req = `${method} ${path} HTTP/1.1\r\nHost: api.shop.com\r\n`;
for (const [k, v] of headers) req += `${k}: ${v}\r\n`;
conn.write(req + "Connection: close\r\n\r\n");
let data = "";
conn.on("data", (d) => (data += d));
conn.on("end", () => {
const cut = data.indexOf("\r\n\r\n");
const [first, h] = parseHead(data.slice(0, cut));
resolve({ status: Number(first.split(" ")[1]), headers: h, body: data.slice(cut + 4) });
});
});
}
// A tiny browser: it follows the CORS rules before letting the page's JavaScript see anything.
async function fetchAs(page, method, path, auth, cookies) {
const label = `${method} ${path} from ${page}${cookies ? " +cookies" : ""}`;
const hs = [];
if (cookies) hs.push(["Cookie", "session=abc"]);
if (auth) hs.push(["Authorization", auth]);
if (page === api) { // same origin: no CORS check at all
const r = await send(method, path, hs);
return `${label} (same origin): ${r.status}, JS reads ${r.body}`;
}
let pre = "";
const simple = ["GET", "HEAD", "POST"].includes(method) && !auth;
if (!simple) { // ask permission first
const p = await send("OPTIONS", path, [["Origin", page],
["Access-Control-Request-Method", method], ["Access-Control-Request-Headers", "authorization"]]);
const ok = p.headers["access-control-allow-origin"] === page &&
(p.headers["access-control-allow-methods"] || "").includes(method) &&
(p.headers["access-control-allow-headers"] || "").toLowerCase().includes("authorization");
if (!ok) return `${label}: preflight failed, ${method} never sent`;
pre = "preflight ok, ";
}
const r = await send(method, path, [["Origin", page], ...hs]);
const acao = r.headers["access-control-allow-origin"] || "";
let blocked = "";
if (acao === "") blocked = "no Access-Control-Allow-Origin";
else if (acao === "*" && cookies) blocked = "wildcard * not allowed with cookies";
else if (acao !== "*" && acao !== page) blocked = "origin does not match";
else if (cookies && r.headers["access-control-allow-credentials"] !== "true") blocked = "credentials not allowed";
if (blocked) return `${label}: ${pre}${r.status}, blocked: ${blocked}`;
return `${label}: ${pre}${r.status}, JS reads ${r.body}`;
}
const server = net.createServer((conn) => {
let head = "";
conn.on("data", (d) => {
head += d;
if (head.includes("\r\n\r\n")) handle(conn, head.slice(0, head.indexOf("\r\n\r\n")));
});
});
server.listen(8097, "127.0.0.1", async () => {
const app = "https://app.shop.com", evil = "https://evil.example";
const lines = [
await fetchAs(api, "GET", "/cart", "", true),
await fetchAs(app, "GET", "/cart", "", true),
await fetchAs(evil, "GET", "/cart", "", true),
await fetchAs(app, "DELETE", "/cart/7", "Bearer t1", false),
await fetchAs(evil, "DELETE", "/cart/7", "Bearer t1", false),
await fetchAs(evil, "GET", "/public", "", false),
await fetchAs(app, "GET", "/public", "", true),
];
lines.forEach((l, i) => console.log(`${i + 1}. ${l}`));
console.log(`server saw ${seen.length} requests: ${seen.join(", ")}`);
server.close();
});use std::collections::HashMap;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, Mutex};
use std::thread;
const API: &str = "https://api.shop.com"; // the server's own origin
const ALLOWED: [&str; 1] = ["https://app.shop.com"];
struct Resp {
status: u16,
headers: HashMap<String, String>,
body: String,
}
// parse_head reads a request or response head and returns its first line and lower-cased headers.
fn parse_head(r: &mut BufReader<TcpStream>) -> (String, HashMap<String, String>) {
let mut first = String::new();
r.read_line(&mut first).unwrap();
let mut h = HashMap::new();
loop {
let mut line = String::new();
if r.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" {
break;
}
if let Some((k, v)) = line.trim_end().split_once(": ") {
h.insert(k.to_lowercase(), v.to_string());
}
}
(first.trim().to_string(), h)
}
// The API server and its CORS policy.
fn handle(conn: TcpStream, seen: &Mutex<Vec<String>>) {
let mut r = BufReader::new(conn.try_clone().unwrap());
let (line, h) = parse_head(&mut r);
let parts: Vec<&str> = line.split_whitespace().collect();
let (method, path) = (parts[0], parts[1]);
seen.lock().unwrap().push(format!("{} {}", method, path));
let origin = h.get("origin").map(String::as_str).unwrap_or("");
let ok_origin = ALLOWED.contains(&origin);
let mut out: HashMap<&str, String> = HashMap::new();
let (mut status, mut body) = (200, "");
if method == "OPTIONS" {
// preflight: say what's allowed, only to origins we trust
status = 204;
if ok_origin {
out.insert("Access-Control-Allow-Origin", origin.to_string());
out.insert("Access-Control-Allow-Methods", "GET, POST, DELETE".into());
out.insert("Access-Control-Allow-Headers", "Authorization, Content-Type".into());
out.insert("Access-Control-Max-Age", "600".into());
}
} else if path == "/public" {
// public data: any site may read it, but not with cookies
out.insert("Access-Control-Allow-Origin", "*".into());
body = r#"{"news":"sale"}"#;
} else {
if ok_origin {
out.insert("Access-Control-Allow-Origin", origin.to_string());
out.insert("Access-Control-Allow-Credentials", "true".into());
}
body = if method == "DELETE" { r#"{"deleted":7}"# } else { r#"{"items":2}"# };
}
let reason = if status == 200 { "OK" } else { "No Content" };
let mut res = format!("HTTP/1.1 {} {}\r\nContent-Length: {}\r\nVary: Origin\r\n", status, reason, body.len());
for k in ["Access-Control-Allow-Origin", "Access-Control-Allow-Credentials",
"Access-Control-Allow-Methods", "Access-Control-Allow-Headers", "Access-Control-Max-Age"] {
if let Some(v) = out.get(k) {
res += &format!("{}: {}\r\n", k, v);
}
}
res += "Connection: close\r\n\r\n";
res += body;
let mut conn = conn;
conn.write_all(res.as_bytes()).unwrap();
}
fn send(method: &str, path: &str, headers: &[(&str, &str)]) -> Resp {
let mut conn = TcpStream::connect("127.0.0.1:8097").unwrap();
let mut req = format!("{} {} HTTP/1.1\r\nHost: api.shop.com\r\n", method, path);
for (k, v) in headers {
req += &format!("{}: {}\r\n", k, v);
}
req += "Connection: close\r\n\r\n";
conn.write_all(req.as_bytes()).unwrap();
let mut r = BufReader::new(conn);
let (first, h) = parse_head(&mut r);
let status = first.split_whitespace().nth(1).unwrap().parse().unwrap();
let mut body = String::new();
r.read_to_string(&mut body).unwrap();
Resp { status, headers: h, body }
}
// A tiny browser: it follows the CORS rules before letting the page's JavaScript see anything.
fn fetch(page: &str, method: &str, path: &str, auth: &str, cookies: bool) -> String {
let label = format!("{} {} from {}{}", method, path, page, if cookies { " +cookies" } else { "" });
let mut hs: Vec<(&str, &str)> = Vec::new();
if cookies {
hs.push(("Cookie", "session=abc"));
}
if !auth.is_empty() {
hs.push(("Authorization", auth));
}
if page == API {
// same origin: no CORS check at all
let r = send(method, path, &hs);
return format!("{} (same origin): {}, JS reads {}", label, r.status, r.body);
}
let get = |h: &HashMap<String, String>, k: &str| h.get(k).cloned().unwrap_or_default();
let mut pre = "";
let simple = ["GET", "HEAD", "POST"].contains(&method) && auth.is_empty();
if !simple {
// ask permission first
let p = send("OPTIONS", path, &[("Origin", page),
("Access-Control-Request-Method", method), ("Access-Control-Request-Headers", "authorization")]);
let ok = get(&p.headers, "access-control-allow-origin") == page
&& get(&p.headers, "access-control-allow-methods").contains(method)
&& get(&p.headers, "access-control-allow-headers").to_lowercase().contains("authorization");
if !ok {
return format!("{}: preflight failed, {} never sent", label, method);
}
pre = "preflight ok, ";
}
let mut all = vec![("Origin", page)];
all.extend(hs);
let r = send(method, path, &all);
let acao = get(&r.headers, "access-control-allow-origin");
let blocked = if acao.is_empty() {
"no Access-Control-Allow-Origin"
} else if acao == "*" && cookies {
"wildcard * not allowed with cookies"
} else if acao != "*" && acao != page {
"origin does not match"
} else if cookies && get(&r.headers, "access-control-allow-credentials") != "true" {
"credentials not allowed"
} else {
""
};
if !blocked.is_empty() {
return format!("{}: {}{}, blocked: {}", label, pre, r.status, blocked);
}
format!("{}: {}{}, JS reads {}", label, pre, r.status, r.body)
}
fn main() {
let seen = Arc::new(Mutex::new(Vec::new())); // every request that reached the server
let ln = TcpListener::bind("127.0.0.1:8097").unwrap();
let s = seen.clone();
thread::spawn(move || {
for c in ln.incoming() {
handle(c.unwrap(), &s);
}
});
let (app, evil) = ("https://app.shop.com", "https://evil.example");
let lines = [
fetch(API, "GET", "/cart", "", true),
fetch(app, "GET", "/cart", "", true),
fetch(evil, "GET", "/cart", "", true),
fetch(app, "DELETE", "/cart/7", "Bearer t1", false),
fetch(evil, "DELETE", "/cart/7", "Bearer t1", false),
fetch(evil, "GET", "/public", "", false),
fetch(app, "GET", "/public", "", true),
];
for (i, l) in lines.iter().enumerate() {
println!("{}. {}", i + 1, l);
}
let seen = seen.lock().unwrap();
println!("server saw {} requests: {}", seen.len(), seen.join(", "));
}import socket
import threading
API = "https://api.shop.com" # the server's own origin
ALLOWED = {"https://app.shop.com"}
seen = [] # every request that reached the server
def parse_head(text):
"""Split a request or response head into its first line and lower-cased headers."""
first, *lines = text.split("\r\n")
h = {}
for line in lines:
k, sep, v = line.partition(": ")
if sep:
h[k.lower()] = v
return first, h
def read_all(conn):
data = b""
while chunk := conn.recv(4096):
data += chunk
return data.decode()
def handle(conn):
"""The API server and its CORS policy."""
head = b""
while b"\r\n\r\n" not in head:
head += conn.recv(4096)
line, h = parse_head(head.decode().split("\r\n\r\n")[0])
method, path = line.split()[:2]
seen.append(f"{method} {path}")
origin = h.get("origin")
out = {}
status, body = 200, ""
if method == "OPTIONS": # preflight: say what's allowed, only to origins we trust
status = 204
if origin in ALLOWED:
out["Access-Control-Allow-Origin"] = origin
out["Access-Control-Allow-Methods"] = "GET, POST, DELETE"
out["Access-Control-Allow-Headers"] = "Authorization, Content-Type"
out["Access-Control-Max-Age"] = "600"
elif path == "/public": # public data: any site may read it, but not with cookies
out["Access-Control-Allow-Origin"] = "*"
body = '{"news":"sale"}'
else:
if origin in ALLOWED:
out["Access-Control-Allow-Origin"] = origin
out["Access-Control-Allow-Credentials"] = "true"
body = '{"deleted":7}' if method == "DELETE" else '{"items":2}'
reason = {200: "OK", 204: "No Content"}[status]
res = f"HTTP/1.1 {status} {reason}\r\nContent-Length: {len(body)}\r\nVary: Origin\r\n"
for k in ["Access-Control-Allow-Origin", "Access-Control-Allow-Credentials",
"Access-Control-Allow-Methods", "Access-Control-Allow-Headers", "Access-Control-Max-Age"]:
if k in out:
res += f"{k}: {out[k]}\r\n"
conn.sendall((res + "Connection: close\r\n\r\n" + body).encode())
conn.close()
def send(method, path, headers):
conn = socket.create_connection(("127.0.0.1", 8097))
req = f"{method} {path} HTTP/1.1\r\nHost: api.shop.com\r\n"
for k, v in headers:
req += f"{k}: {v}\r\n"
conn.sendall((req + "Connection: close\r\n\r\n").encode())
data = read_all(conn)
conn.close()
head, _, body = data.partition("\r\n\r\n")
first, h = parse_head(head)
return int(first.split()[1]), h, body
def fetch(page, method, path, auth, cookies):
"""A tiny browser: it follows the CORS rules before letting the page's JavaScript see anything."""
label = f"{method} {path} from {page}{' +cookies' if cookies else ''}"
hs = []
if cookies:
hs.append(("Cookie", "session=abc"))
if auth:
hs.append(("Authorization", auth))
if page == API: # same origin: no CORS check at all
status, _, body = send(method, path, hs)
return f"{label} (same origin): {status}, JS reads {body}"
pre = ""
simple = method in ("GET", "HEAD", "POST") and not auth
if not simple: # ask permission first
_, p, _ = send("OPTIONS", path, [("Origin", page),
("Access-Control-Request-Method", method), ("Access-Control-Request-Headers", "authorization")])
ok = (p.get("access-control-allow-origin") == page
and method in p.get("access-control-allow-methods", "")
and "authorization" in p.get("access-control-allow-headers", "").lower())
if not ok:
return f"{label}: preflight failed, {method} never sent"
pre = "preflight ok, "
status, h, body = send(method, path, [("Origin", page)] + hs)
acao = h.get("access-control-allow-origin", "")
blocked = ""
if acao == "":
blocked = "no Access-Control-Allow-Origin"
elif acao == "*" and cookies:
blocked = "wildcard * not allowed with cookies"
elif acao != "*" and acao != page:
blocked = "origin does not match"
elif cookies and h.get("access-control-allow-credentials") != "true":
blocked = "credentials not allowed"
if blocked:
return f"{label}: {pre}{status}, blocked: {blocked}"
return f"{label}: {pre}{status}, JS reads {body}"
def serve(ln):
while True:
conn, _ = ln.accept()
handle(conn)
ln = socket.socket()
ln.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ln.bind(("127.0.0.1", 8097))
ln.listen()
threading.Thread(target=serve, args=(ln,), daemon=True).start()
app, evil = "https://app.shop.com", "https://evil.example"
lines = [
fetch(API, "GET", "/cart", "", True),
fetch(app, "GET", "/cart", "", True),
fetch(evil, "GET", "/cart", "", True),
fetch(app, "DELETE", "/cart/7", "Bearer t1", False),
fetch(evil, "DELETE", "/cart/7", "Bearer t1", False),
fetch(evil, "GET", "/public", "", False),
fetch(app, "GET", "/public", "", True),
]
for i, l in enumerate(lines, 1):
print(f"{i}. {l}")
print(f"server saw {len(seen)} requests: {', '.join(seen)}")import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class Main {
static final String API = "https://api.shop.com"; // the server's own origin
static final Set<String> ALLOWED = Set.of("https://app.shop.com");
static final List<String> seen = Collections.synchronizedList(new ArrayList<>()); // every request that reached the server
record Resp(int status, Map<String, String> headers, String body) {}
// readLine reads one CRLF-terminated line from a raw stream.
static String readLine(InputStream in) throws IOException {
StringBuilder sb = new StringBuilder();
int c;
while ((c = in.read()) != -1) {
sb.append((char) c);
if (c == '\n') break;
}
return sb.toString();
}
// parseHead reads a request or response head: its first line, then lower-cased headers.
static Map<String, String> parseHead(InputStream in, String[] first) throws IOException {
first[0] = readLine(in).trim();
Map<String, String> h = new HashMap<>();
while (true) {
String line = readLine(in);
if (line.isEmpty() || line.equals("\r\n")) break;
String t = line.stripTrailing();
int i = t.indexOf(": ");
if (i > 0) h.put(t.substring(0, i).toLowerCase(), t.substring(i + 2));
}
return h;
}
// The API server and its CORS policy.
static void handle(Socket conn) throws IOException {
String[] line = new String[1];
Map<String, String> h = parseHead(conn.getInputStream(), line);
String[] parts = line[0].split(" ");
String method = parts[0], path = parts[1];
seen.add(method + " " + path);
String origin = h.getOrDefault("origin", "");
Map<String, String> out = new HashMap<>();
int status = 200;
String body = "";
if (method.equals("OPTIONS")) { // preflight: say what's allowed, only to origins we trust
status = 204;
if (ALLOWED.contains(origin)) {
out.put("Access-Control-Allow-Origin", origin);
out.put("Access-Control-Allow-Methods", "GET, POST, DELETE");
out.put("Access-Control-Allow-Headers", "Authorization, Content-Type");
out.put("Access-Control-Max-Age", "600");
}
} else if (path.equals("/public")) { // public data: any site may read it, but not with cookies
out.put("Access-Control-Allow-Origin", "*");
body = "{\"news\":\"sale\"}";
} else {
if (ALLOWED.contains(origin)) {
out.put("Access-Control-Allow-Origin", origin);
out.put("Access-Control-Allow-Credentials", "true");
}
body = method.equals("DELETE") ? "{\"deleted\":7}" : "{\"items\":2}";
}
String reason = status == 200 ? "OK" : "No Content";
StringBuilder res = new StringBuilder("HTTP/1.1 " + status + " " + reason + "\r\nContent-Length: " + body.length() + "\r\nVary: Origin\r\n");
for (String k : List.of("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials",
"Access-Control-Allow-Methods", "Access-Control-Allow-Headers", "Access-Control-Max-Age")) {
if (out.containsKey(k)) res.append(k).append(": ").append(out.get(k)).append("\r\n");
}
res.append("Connection: close\r\n\r\n").append(body);
conn.getOutputStream().write(res.toString().getBytes(StandardCharsets.UTF_8));
conn.close();
}
static Resp send(String method, String path, List<String[]> headers) throws IOException {
try (Socket conn = new Socket("127.0.0.1", 8097)) {
StringBuilder req = new StringBuilder(method + " " + path + " HTTP/1.1\r\nHost: api.shop.com\r\n");
for (String[] kv : headers) req.append(kv[0]).append(": ").append(kv[1]).append("\r\n");
req.append("Connection: close\r\n\r\n");
conn.getOutputStream().write(req.toString().getBytes(StandardCharsets.UTF_8));
InputStream in = conn.getInputStream();
String[] first = new String[1];
Map<String, String> h = parseHead(in, first);
String body = new String(in.readAllBytes(), StandardCharsets.UTF_8);
return new Resp(Integer.parseInt(first[0].split(" ")[1]), h, body);
}
}
// A tiny browser: it follows the CORS rules before letting the page's JavaScript see anything.
static String fetch(String page, String method, String path, String auth, boolean cookies) throws IOException {
String label = method + " " + path + " from " + page + (cookies ? " +cookies" : "");
List<String[]> hs = new ArrayList<>();
if (cookies) hs.add(new String[]{"Cookie", "session=abc"});
if (!auth.isEmpty()) hs.add(new String[]{"Authorization", auth});
if (page.equals(API)) { // same origin: no CORS check at all
Resp r = send(method, path, hs);
return label + " (same origin): " + r.status() + ", JS reads " + r.body();
}
String pre = "";
boolean simple = List.of("GET", "HEAD", "POST").contains(method) && auth.isEmpty();
if (!simple) { // ask permission first
Resp p = send("OPTIONS", path, List.of(new String[]{"Origin", page},
new String[]{"Access-Control-Request-Method", method}, new String[]{"Access-Control-Request-Headers", "authorization"}));
boolean ok = page.equals(p.headers().get("access-control-allow-origin"))
&& p.headers().getOrDefault("access-control-allow-methods", "").contains(method)
&& p.headers().getOrDefault("access-control-allow-headers", "").toLowerCase().contains("authorization");
if (!ok) return label + ": preflight failed, " + method + " never sent";
pre = "preflight ok, ";
}
List<String[]> all = new ArrayList<>();
all.add(new String[]{"Origin", page});
all.addAll(hs);
Resp r = send(method, path, all);
String acao = r.headers().getOrDefault("access-control-allow-origin", "");
String blocked = "";
if (acao.isEmpty()) blocked = "no Access-Control-Allow-Origin";
else if (acao.equals("*") && cookies) blocked = "wildcard * not allowed with cookies";
else if (!acao.equals("*") && !acao.equals(page)) blocked = "origin does not match";
else if (cookies && !"true".equals(r.headers().get("access-control-allow-credentials"))) blocked = "credentials not allowed";
if (!blocked.isEmpty()) return label + ": " + pre + r.status() + ", blocked: " + blocked;
return label + ": " + pre + r.status() + ", JS reads " + r.body();
}
public static void main(String[] args) throws Exception {
ServerSocket ln = new ServerSocket(8097, 50, InetAddress.getByName("127.0.0.1"));
Thread t = new Thread(() -> {
while (true) {
try { handle(ln.accept()); } catch (IOException e) { return; }
}
});
t.setDaemon(true);
t.start();
String app = "https://app.shop.com", evil = "https://evil.example";
List<String> lines = List.of(
fetch(API, "GET", "/cart", "", true),
fetch(app, "GET", "/cart", "", true),
fetch(evil, "GET", "/cart", "", true),
fetch(app, "DELETE", "/cart/7", "Bearer t1", false),
fetch(evil, "DELETE", "/cart/7", "Bearer t1", false),
fetch(evil, "GET", "/public", "", false),
fetch(app, "GET", "/public", "", true));
for (int i = 0; i < lines.size(); i++) System.out.println((i + 1) + ". " + lines.get(i));
System.out.println("server saw " + seen.size() + " requests: " + String.join(", ", seen));
}
}Output (the same in all five languages):
1. GET /cart from https://api.shop.com +cookies (same origin): 200, JS reads {"items":2}
2. GET /cart from https://app.shop.com +cookies: 200, JS reads {"items":2}
3. GET /cart from https://evil.example +cookies: 200, blocked: no Access-Control-Allow-Origin
4. DELETE /cart/7 from https://app.shop.com: preflight ok, 200, JS reads {"deleted":7}
5. DELETE /cart/7 from https://evil.example: preflight failed, DELETE never sent
6. GET /public from https://evil.example: 200, JS reads {"news":"sale"}
7. GET /public from https://app.shop.com +cookies: 200, blocked: wildcard * not allowed with cookies
server saw 8 requests: GET /cart, GET /cart, GET /cart, OPTIONS /cart/7, DELETE /cart/7, OPTIONS /cart/7, GET /public, GET /public
Reading the output:
- Line 1, same origin: no CORS check. The page reads the cart.
- Line 2, trusted origin with cookies: the server echoed
https://app.shop.comandAllow-Credentials: true, so JavaScript reads it. - Line 3 is the important one. evil.example's GET got a 200: the server ran the handler with the user's cookie. The browser only stopped the page from reading it. Look at the last line: the server saw three
GET /cartrequests, including evil's. - Lines 4 and 5, DELETE: the trusted page got
preflight okand then the DELETE. For evil.example the preflight answer had no allow header, so the DELETE never left the browser. The server log shows onlyOPTIONS /cart/7for it, no second DELETE. - Line 6:
/publicsends*, so even evil.example may read it without cookies. - Line 7: the same
*with cookies is blocked, even for the trusted origin. Wildcards and credentials never mix.
And a real API, GitHub, answering a preflight from a made-up origin:
$ curl -s -o /dev/null -D - -X OPTIONS https://api.github.com/user -H "Origin: https://evil.example" -H "Access-Control-Request-Method: DELETE" -H "Access-Control-Request-Headers: authorization" | grep -iE "^(HTTP|access-control-allow-(origin|methods)|access-control-max-age)"
HTTP/2 204
access-control-max-age: 86400
access-control-allow-methods: GET, POST, PATCH, PUT, DELETE
access-control-allow-origin: *
$ curl -s -o /dev/null -D - https://www.google.com/ -H "Origin: https://evil.example" | grep -ciE "^access-control"
0
204withallow-origin: *: GitHub's API lets any website call it. That's safe for them because the API is authenticated with tokens in theAuthorizationheader, not cookies, and*can never be combined with cookies.max-age: 86400: browsers may cache this preflight for up to a day (Chrome caps it at 2 hours).- google.com's home page sends 0 CORS headers: it's an HTML page, not an API, so no other site may read it with
fetch.
Real engineering
- Keep an explicit allowlist of origins, per environment:
https://app.shop.comin production,http://localhost:3000only in development. Compare exact strings. - Use your framework's CORS middleware (Go
rs/cors, Expresscors, Spring@CrossOrigin/CorsConfiguration, FastAPICORSMiddleware) instead of hand-writing headers, and configure it rather than turning on "allow all". - Answer
OPTIONSbefore auth. Preflights carry no cookies or tokens. If your auth middleware rejects them with 401, every non-simple request fails. - Set
Access-Control-Max-Ageto cut preflight round trips, and sendVary: Originwhen the allowed origin depends on the request. - Expose the headers the frontend needs. By default JavaScript can read only a few response headers. Use
Access-Control-Expose-Headers: ETag, Location, X-Request-Idfor the rest. - Avoid CORS entirely when you can: serve the frontend and API from the same origin (
shop.comandshop.com/api) through a reverse proxy. No preflights, no configuration, cookies just work. - CORS is not CSRF protection. Simple cross-origin POSTs still reach your server with cookies. Use
SameSitecookies, CSRF tokens or require a JSON content type for state-changing requests.
When it breaks
Pick a failure
No 'Access-Control-Allow-Origin' header is present
Think before you read on
If CORS doesn't stop the server from receiving a simple cross-origin POST, why do browsers bother with preflights for DELETE and JSON requests at all?
Reveal
Because of what was already possible before CORS existed. An HTML <form> on any website could always POST to any other site, with cookies, using form encoding. Servers had to defend against that anyway (CSRF). So letting fetch send the same kinds of requests adds no new danger. But no old web page could send a DELETE, a JSON body or a custom Authorization header to another site. Many servers were written assuming those only come from their own pages. The preflight protects those servers: it asks first, and older servers that know nothing about CORS answer without the allow headers, so the risky request is never sent.
Check yourself
1. What makes two URLs the same origin?
Answer
The same scheme, host and port. https://shop.com/a and https://shop.com/b are the same origin; https://shop.com and https://api.shop.com are not.
2. Who enforces CORS: the server or the browser?
Answer
The browser. The server only sends headers saying which origins, methods and headers it allows. curl, mobile apps and other servers ignore them.
3. Which requests trigger a preflight?
Answer
Anything that isn't a simple request: methods other than GET, HEAD and POST, custom headers such as Authorization, or a Content-Type other than text/plain, form data or multipart (for example application/json).
4. Why can't you use Access-Control-Allow-Origin: * with cookies?
Answer
Because that would let every website read responses made with the user's cookies. With credentials, the browser requires the exact origin and Access-Control-Allow-Credentials: true.
Your challenge: add a preflight cache
Extend the tiny browser in the code:
- Keep a preflight cache keyed by
(origin, method, path). When a preflight succeeds, store it with an expiry fromAccess-Control-Max-Age, using a fake clock you advance by hand. - Before preflighting, check the cache; skip the
OPTIONSrequest if there's a fresh entry. - From
https://app.shop.com, sendDELETE /cart/7three times, advance the clock by 700 seconds, and send it once more.
Before you run it, predict how many OPTIONS requests the server will see.
You've succeeded when the server log shows 2 OPTIONS /cart/7 and 4 DELETE /cart/7, and changing the server's Max-Age to 0 makes it 4 and 4.
The mental model
The same-origin policy stops a page from reading another origin's responses, because the browser carries the user's cookies everywhere. CORS lets a server grant exceptions with headers: Allow-Origin, Allow-Methods, Allow-Headers, Allow-Credentials. The browser enforces them, sending simple requests straight away and preflighting the rest with OPTIONS. Use an exact allowlist, answer preflights before auth, never pair
*with credentials, and remember that CORS protects users' data in the browser, not your server.
Station stamp
Finish the chapter
Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.
Go Pro to earn XP →