CORS

suggest change

Browsers enforce the same-origin policy: JavaScript on a page can send requests anywhere, but it can read a response only if the response comes from the page's own origin. An origin is the scheme, host and port together:

URL Same origin as https://app.example.com?
https://app.example.com/settings yes, only the path differs
http://app.example.com no, different scheme
https://api.example.com no, different host (subdomains count)
https://app.example.com:8443 no, different port

A single-page app on https://app.example.com that calls an API on https://api.example.com is therefore making a cross-origin request. Cross-Origin Resource Sharing (CORS) lets the API server say which other origins may read its responses. The browser sends an Origin header with the request, and the server answers with Access-Control-Allow-* headers:

GET /api/profile HTTP/1.1
Host: api.example.com
Origin: https://app.example.com

HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://app.example.com
Vary: Origin
Content-Type: application/json

Three facts explain most CORS confusion:

This article implements CORS for the JDK's built-in com.sun.net.httpserver.HttpServer, first by hand and then as a reusable Filter. It ends with the CORS support in Spring. Each example is a single file you can run with java Example.java. Servers bind to a free port (new InetSocketAddress("localhost", 0)), and HttpClient plays the browser by sending the Origin header itself. All output comes from JDK 25.

See A minimal HTTP server for the basics of HttpServer, HTTP headers for headers in general, HTTP middleware for filters and Cookies for the cookies that credentialed requests send.

The CORS headers

Header Direction Meaning
Origin request Origin of the page making the request. Set by the browser, JavaScript can't change it
Access-Control-Request-Method preflight request Method the actual request will use
Access-Control-Request-Headers preflight request Non-safelisted headers the actual request will send, lower case, comma separated
Access-Control-Allow-Origin response The one origin allowed to read the response, or * for any
Access-Control-Allow-Methods preflight response Methods allowed for the actual request
Access-Control-Allow-Headers preflight response Request headers allowed for the actual request
Access-Control-Max-Age preflight response How many seconds the browser may cache the preflight result
Access-Control-Allow-Credentials response true lets the page send cookies and read the response
Access-Control-Expose-Headers response Response headers JavaScript may read, beyond the safelisted ones

Simple requests

Some requests the browser sends right away, with an Origin header. These simple requests are the ones an HTML form could send anyway: GET, HEAD or POST, with only safelisted headers (Accept, Accept-Language, Content-Language, Content-Type), and a Content-Type of application/x-www-form-urlencoded, multipart/form-data or text/plain.

For those the server only has to add Access-Control-Allow-Origin to the response. Check the origin against an allowlist and echo it back:

import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;

public class SimpleCors {
    static final String ALLOWED_ORIGIN = "https://app.example.com";

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
        server.createContext("/api/hello", ex -> {
            String origin = ex.getRequestHeaders().getFirst("Origin");
            if (ALLOWED_ORIGIN.equals(origin)) {
                ex.getResponseHeaders().set("Access-Control-Allow-Origin", origin);
            }
            // The response depends on Origin, so caches must key on it
            ex.getResponseHeaders().add("Vary", "Origin");
            byte[] body = "{\"msg\":\"hello\"}".getBytes(StandardCharsets.UTF_8);
            ex.getResponseHeaders().set("Content-Type", "application/json");
            ex.sendResponseHeaders(200, body.length);
            try (var out = ex.getResponseBody()) { out.write(body); }
        });
        server.start();
        URI uri = URI.create("http://localhost:" + server.getAddress().getPort() + "/api/hello");

        HttpClient client = HttpClient.newHttpClient();
        for (String origin : new String[] {null, "https://app.example.com", "https://evil.example"}) {
            var b = HttpRequest.newBuilder(uri);
            if (origin != null) b.header("Origin", origin);
            HttpResponse<String> resp = client.send(b.build(), HttpResponse.BodyHandlers.ofString());
            System.out.printf("%-32s -> %d %s, Allow-Origin: %s%n",
                origin == null ? "(no Origin)" : "Origin: " + origin, resp.statusCode(), resp.body(),
                resp.headers().firstValue("Access-Control-Allow-Origin").orElse("(none)"));
        }
        server.stop(0);
    }
}

Output:

(no Origin)                      -> 200 {"msg":"hello"}, Allow-Origin: (none)
Origin: https://app.example.com  -> 200 {"msg":"hello"}, Allow-Origin: https://app.example.com
Origin: https://evil.example     -> 200 {"msg":"hello"}, Allow-Origin: (none)

Notice that the server sends the same 200 and body to every origin. For https://evil.example the browser receives the response too, but because there's no matching Access-Control-Allow-Origin it rejects it and fetch() fails with a TypeError. The request without Origin is what a same-origin request or a non-browser client looks like. It doesn't need CORS headers.

Vary: Origin tells caches (browsers, CDNs, proxies) that the response depends on the Origin request header. Without it, a CDN could cache the response for https://app.example.com and serve it, Access-Control-Allow-Origin header included, to other origins, or cache the response without the header and break your own app. Send Vary: Origin whenever the CORS headers depend on the origin, even on responses that don't allow it.

If the API is public, has no cookies or auth and anyone may call it, Access-Control-Allow-Origin: * is simpler and needs no Vary.

Preflight requests

Everything else is "non-simple": PUT, PATCH and DELETE, a JSON Content-Type, an Authorization header or any custom header. Before sending such a request, the browser asks the server for permission with a preflight: an OPTIONS request that carries Origin, Access-Control-Request-Method and Access-Control-Request-Headers. The browser sends the actual request only if the preflight response allows the origin, the method and every header:

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Set;

public class Preflight {
    static final String ALLOWED_ORIGIN = "https://app.example.com";

    static void handle(HttpExchange ex) throws IOException {
        var req = ex.getRequestHeaders();
        var resp = ex.getResponseHeaders();
        String origin = req.getFirst("Origin");
        boolean allowed = ALLOWED_ORIGIN.equals(origin);
        resp.add("Vary", "Origin");

        // A preflight is OPTIONS + Origin + Access-Control-Request-Method
        if (ex.getRequestMethod().equals("OPTIONS")
                && origin != null && req.containsKey("Access-Control-Request-Method")) {
            resp.add("Vary", "Access-Control-Request-Method");
            resp.add("Vary", "Access-Control-Request-Headers");
            if (allowed) {
                resp.set("Access-Control-Allow-Origin", origin);
                resp.set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
                resp.set("Access-Control-Allow-Headers", "Content-Type, Authorization");
                resp.set("Access-Control-Max-Age", "600");
            }
            ex.sendResponseHeaders(204, -1);   // no body, no handler call
            ex.close();
            return;
        }

        // The actual request still needs Access-Control-Allow-Origin
        if (allowed) resp.set("Access-Control-Allow-Origin", origin);
        String text = ex.getRequestMethod() + " handled";
        byte[] body = text.getBytes(StandardCharsets.UTF_8);
        ex.sendResponseHeaders(200, body.length);
        try (var out = ex.getResponseBody()) { out.write(body); }
    }

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
        server.createContext("/api/items/42", Preflight::handle);
        server.start();
        URI uri = URI.create("http://localhost:" + server.getAddress().getPort() + "/api/items/42");
        HttpClient client = HttpClient.newHttpClient();

        // 1. What the browser sends before fetch(url, {method: "PUT", headers: {...}})
        HttpRequest preflight = HttpRequest.newBuilder(uri)
            .method("OPTIONS", HttpRequest.BodyPublishers.noBody())
            .header("Origin", ALLOWED_ORIGIN)
            .header("Access-Control-Request-Method", "PUT")
            .header("Access-Control-Request-Headers", "authorization,content-type")
            .build();
        HttpResponse<Void> pre = client.send(preflight, HttpResponse.BodyHandlers.discarding());
        System.out.println("preflight -> " + pre.statusCode());
        pre.headers().map().forEach((k, v) -> {
            if (k.startsWith("access-control") || k.equals("vary")) System.out.println("  " + k + ": " + v);
        });

        // 2. The actual request, sent only if the preflight allowed it
        HttpRequest put = HttpRequest.newBuilder(uri)
            .PUT(HttpRequest.BodyPublishers.ofString("{\"name\":\"new\"}"))
            .header("Origin", ALLOWED_ORIGIN)
            .header("Content-Type", "application/json")
            .header("Authorization", "Bearer abc")
            .build();
        HttpResponse<String> actual = client.send(put, HttpResponse.BodyHandlers.ofString());
        System.out.println("actual    -> " + actual.statusCode() + " " + actual.body()
            + ", Allow-Origin: " + actual.headers().firstValue("Access-Control-Allow-Origin").orElse("(none)"));
        server.stop(0);
    }
}

Output:

preflight -> 204
  access-control-allow-headers: [Content-Type, Authorization]
  access-control-allow-methods: [GET, POST, PUT, DELETE]
  access-control-allow-origin: [https://app.example.com]
  access-control-max-age: [600]
  vary: [Origin, Access-Control-Request-Method, Access-Control-Request-Headers]
actual    -> 200 PUT handled, Allow-Origin: https://app.example.com

The first request is what the browser sends before this JavaScript runs:

fetch("https://api.example.com/api/items/42", {
  method: "PUT",
  headers: { "Content-Type": "application/json", "Authorization": "Bearer abc" },
  body: JSON.stringify({ name: "new" }),
});

Points to note:

Distinguish a preflight from an ordinary OPTIONS request by the Access-Control-Request-Method header. Only the browser's preflight has it.

A reusable CORS filter

Putting CORS into every handler doesn't scale. As a Filter it's configured once and runs before all handlers of a context. The filter below takes a policy record, answers preflights without calling the handler, and adds the headers to the actual responses. It's installed in front of an authentication filter, so preflights are answered before anyone looks for a session cookie:

import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

public class CorsFilter {
    record CorsPolicy(Set<String> origins, Set<String> methods, Set<String> headers,
                      List<String> exposedHeaders, boolean allowCredentials, Duration maxAge) {
        CorsPolicy {
            if (allowCredentials && origins.contains("*")) {
                throw new IllegalArgumentException("credentials can't be combined with origin *");
            }
            methods = new TreeSet<>(methods);
            // header names are case-insensitive: compare them in lower case
            headers = headers.stream().map(h -> h.toLowerCase(Locale.ROOT))
                .collect(Collectors.toCollection(TreeSet::new));
        }

        boolean originAllowed(String origin) {
            return origins.contains("*") || origins.contains(origin);
        }
    }

    static Filter cors(CorsPolicy policy) {
        return new Filter() {
            @Override public String description() { return "CORS"; }

            @Override public void doFilter(HttpExchange ex, Chain chain) throws IOException {
                Headers req = ex.getRequestHeaders();
                Headers resp = ex.getResponseHeaders();
                String origin = req.getFirst("Origin");
                resp.add("Vary", "Origin");
                if (origin == null) {               // same-origin or non-browser client
                    chain.doFilter(ex);
                    return;
                }
                String allowOrigin = policy.origins().contains("*") ? "*" : origin;

                String requestMethod = req.getFirst("Access-Control-Request-Method");
                if (ex.getRequestMethod().equals("OPTIONS") && requestMethod != null) {
                    resp.add("Vary", "Access-Control-Request-Method");
                    resp.add("Vary", "Access-Control-Request-Headers");
                    String rawHeaders = req.getFirst("Access-Control-Request-Headers");
                    List<String> requested = rawHeaders == null ? List.of()
                        : Arrays.stream(rawHeaders.split(","))
                            .map(h -> h.trim().toLowerCase(Locale.ROOT))
                            .filter(h -> !h.isEmpty()).toList();
                    if (policy.originAllowed(origin)
                            && policy.methods().contains(requestMethod)
                            && policy.headers().containsAll(requested)) {
                        resp.set("Access-Control-Allow-Origin", allowOrigin);
                        resp.set("Access-Control-Allow-Methods", String.join(", ", policy.methods()));
                        if (!requested.isEmpty()) {
                            resp.set("Access-Control-Allow-Headers", String.join(", ", requested));
                        }
                        if (policy.allowCredentials()) {
                            resp.set("Access-Control-Allow-Credentials", "true");
                        }
                        resp.set("Access-Control-Max-Age", String.valueOf(policy.maxAge().toSeconds()));
                    }
                    // Answer every preflight with 204. Without the headers above the browser blocks it.
                    ex.sendResponseHeaders(204, -1);
                    ex.close();
                    return;
                }

                if (policy.originAllowed(origin)) {
                    resp.set("Access-Control-Allow-Origin", allowOrigin);
                    if (policy.allowCredentials()) {
                        resp.set("Access-Control-Allow-Credentials", "true");
                    }
                    if (!policy.exposedHeaders().isEmpty()) {
                        resp.set("Access-Control-Expose-Headers",
                            String.join(", ", policy.exposedHeaders()));
                    }
                }
                chain.doFilter(ex);
            }
        };
    }

    // Rejects requests without a session cookie. Runs after CORS, so preflights never get here.
    static Filter requireSession() {
        return new Filter() {
            @Override public String description() { return "auth"; }

            @Override public void doFilter(HttpExchange ex, Chain chain) throws IOException {
                String cookie = ex.getRequestHeaders().getFirst("Cookie");
                if (cookie == null || !cookie.contains("session=")) {
                    ex.sendResponseHeaders(401, -1);
                    ex.close();
                    return;
                }
                chain.doFilter(ex);
            }
        };
    }

    public static void main(String[] args) throws Exception {
        CorsPolicy policy = new CorsPolicy(
            Set.of("https://app.example.com", "http://localhost:5173"),
            Set.of("GET", "POST", "PUT", "DELETE"),
            Set.of("Content-Type", "Authorization"),
            List.of("X-Request-Id"),
            true,
            Duration.ofMinutes(10));

        HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
        var ctx = server.createContext("/api/profile", ex -> {
            ex.getResponseHeaders().set("X-Request-Id", "r-1001");
            ex.getResponseHeaders().set("Content-Type", "application/json");
            byte[] body = "{\"user\":\"alice\"}".getBytes(StandardCharsets.UTF_8);
            ex.sendResponseHeaders(200, body.length);
            try (var out = ex.getResponseBody()) { out.write(body); }
        });
        ctx.getFilters().add(cors(policy));      // CORS first
        ctx.getFilters().add(requireSession());  // then authentication
        server.start();
        URI uri = URI.create("http://localhost:" + server.getAddress().getPort() + "/api/profile");
        HttpClient client = HttpClient.newHttpClient();

        // GET with a session cookie, as fetch(url, {credentials: "include"}) sends it
        get(client, uri, "https://app.example.com");
        get(client, uri, "https://evil.example");
        preflight(client, uri, "https://app.example.com", "PUT", "content-type,authorization");
        preflight(client, uri, "https://app.example.com", "PATCH", "content-type");
        preflight(client, uri, "https://app.example.com", "PUT", "x-debug");
        preflight(client, uri, "https://evil.example", "PUT", "content-type");
        server.stop(0);
    }

    static void get(HttpClient client, URI uri, String origin) throws Exception {
        HttpRequest req = HttpRequest.newBuilder(uri)
            .header("Origin", origin)
            .header("Cookie", "session=s3cr3t")
            .build();
        print("GET from " + origin, client.send(req, HttpResponse.BodyHandlers.ofString()));
    }

    static void preflight(HttpClient client, URI uri, String origin, String method,
                          String headers) throws Exception {
        HttpRequest req = HttpRequest.newBuilder(uri)
            .method("OPTIONS", HttpRequest.BodyPublishers.noBody())
            .header("Origin", origin)
            .header("Access-Control-Request-Method", method)
            .header("Access-Control-Request-Headers", headers)
            .build();
        print("preflight " + method + " [" + headers + "] from " + origin,
            client.send(req, HttpResponse.BodyHandlers.ofString()));
    }

    static void print(String label, HttpResponse<String> resp) {
        System.out.println(label + " -> " + resp.statusCode()
            + (resp.body().isEmpty() ? "" : " " + resp.body()));
        resp.headers().map().forEach((name, values) -> {
            if (name.startsWith("access-control")) {
                System.out.println("    " + name + ": " + String.join(", ", values));
            }
        });
    }
}

Output:

GET from https://app.example.com -> 200 {"user":"alice"}
    access-control-allow-credentials: true
    access-control-allow-origin: https://app.example.com
    access-control-expose-headers: X-Request-Id
GET from https://evil.example -> 200 {"user":"alice"}
preflight PUT [content-type,authorization] from https://app.example.com -> 204
    access-control-allow-credentials: true
    access-control-allow-headers: content-type, authorization
    access-control-allow-methods: DELETE, GET, POST, PUT
    access-control-allow-origin: https://app.example.com
    access-control-max-age: 600
preflight PATCH [content-type] from https://app.example.com -> 204
preflight PUT [x-debug] from https://app.example.com -> 204
preflight PUT [content-type] from https://evil.example -> 204

How the browser reads this:

The filter echoes back the requested headers instead of the whole allowed list, which is common. Either works, the browser only checks that every requested header appears in Access-Control-Allow-Headers.

Order matters for filters: CORS must come before authentication, rate limiting and anything else that can reject a request. Error responses need CORS headers too. If a 401 or 429 lacks Access-Control-Allow-Origin, the browser reports a CORS error and the page never sees the real status code. See HTTP middleware for more on filter ordering.

How the browser decides

Most CORS bugs come from responses that look almost right. This program is a simplified model of the checks browsers run, useful for understanding the error messages they print in the console:

import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

// A simplified version of the checks a browser runs on a cross-origin response
public class BrowserCheck {
    static final Set<String> SIMPLE_METHODS = Set.of("GET", "HEAD", "POST");
    static final Set<String> SAFELISTED_HEADERS =
        Set.of("accept", "accept-language", "content-language", "content-type");
    static final Set<String> SIMPLE_CONTENT_TYPES =
        Set.of("application/x-www-form-urlencoded", "multipart/form-data", "text/plain");

    static boolean needsPreflight(String method, Map<String, String> headers) {
        if (!SIMPLE_METHODS.contains(method)) return true;
        for (var e : headers.entrySet()) {
            String name = e.getKey().toLowerCase(Locale.ROOT);
            if (!SAFELISTED_HEADERS.contains(name)) return true;
            if (name.equals("content-type")) {
                String mime = e.getValue().split(";")[0].trim().toLowerCase(Locale.ROOT);
                if (!SIMPLE_CONTENT_TYPES.contains(mime)) return true;
            }
        }
        return false;
    }

    // Can the page at `origin` read this response?
    static String check(String origin, boolean credentials, Map<String, List<String>> resp) {
        List<String> acao = resp.getOrDefault("Access-Control-Allow-Origin", List.of());
        if (acao.isEmpty()) return "blocked: no Access-Control-Allow-Origin";
        if (acao.size() > 1 || acao.getFirst().contains(",")) {
            return "blocked: Access-Control-Allow-Origin has multiple values";
        }
        String value = acao.getFirst();
        if (value.equals("*")) {
            return credentials ? "blocked: * is not allowed with credentials" : "allowed";
        }
        if (!value.equals(origin)) return "blocked: " + value + " != " + origin;
        if (credentials && !resp.getOrDefault("Access-Control-Allow-Credentials", List.of())
                .equals(List.of("true"))) {
            return "blocked: credentials need Access-Control-Allow-Credentials: true";
        }
        return "allowed";
    }

    public static void main(String[] args) {
        System.out.println("GET, no headers:               preflight=" + needsPreflight("GET", Map.of()));
        System.out.println("POST, form data:               preflight="
            + needsPreflight("POST", Map.of("Content-Type", "application/x-www-form-urlencoded")));
        System.out.println("POST, JSON:                    preflight="
            + needsPreflight("POST", Map.of("Content-Type", "application/json")));
        System.out.println("GET, Authorization:            preflight="
            + needsPreflight("GET", Map.of("Authorization", "Bearer abc")));
        System.out.println("DELETE:                        preflight=" + needsPreflight("DELETE", Map.of()));
        System.out.println();

        String app = "https://app.example.com";
        record Case(String name, boolean credentials, Map<String, List<String>> headers) {}
        List<Case> cases = List.of(
            new Case("no CORS headers", false, Map.of()),
            new Case("wildcard", false, Map.of("Access-Control-Allow-Origin", List.of("*"))),
            new Case("wildcard + cookies", true, Map.of("Access-Control-Allow-Origin", List.of("*"))),
            new Case("exact origin", false, Map.of("Access-Control-Allow-Origin", List.of(app))),
            new Case("exact origin + cookies, no ACAC", true,
                Map.of("Access-Control-Allow-Origin", List.of(app))),
            new Case("exact origin + cookies", true, Map.of(
                "Access-Control-Allow-Origin", List.of(app),
                "Access-Control-Allow-Credentials", List.of("true"))),
            new Case("list of origins", false, Map.of("Access-Control-Allow-Origin",
                List.of("https://app.example.com, https://admin.example.com"))),
            new Case("trailing slash", false, Map.of("Access-Control-Allow-Origin",
                List.of("https://app.example.com/"))));
        for (Case c : cases) {
            System.out.printf("%-33s %s%n", c.name(), check(app, c.credentials(), c.headers()));
        }
    }
}

Output:

GET, no headers:               preflight=false
POST, form data:               preflight=false
POST, JSON:                    preflight=true
GET, Authorization:            preflight=true
DELETE:                        preflight=true

no CORS headers                   blocked: no Access-Control-Allow-Origin
wildcard                          allowed
wildcard + cookies                blocked: * is not allowed with credentials
exact origin                      allowed
exact origin + cookies, no ACAC   blocked: credentials need Access-Control-Allow-Credentials: true
exact origin + cookies            allowed
list of origins                   blocked: Access-Control-Allow-Origin has multiple values
trailing slash                    blocked: https://app.example.com/ != https://app.example.com

Access-Control-Allow-Origin holds exactly one origin or *. There's no list syntax, which is why a server that supports several origins has to compare the request's Origin against its allowlist and echo back the one that matched. The value is compared as a string, so a trailing slash or http instead of https is enough to fail.

Credentials

By default fetch() doesn't send cookies or HTTP authentication on cross-origin requests. With fetch(url, { credentials: "include" }) (or xhr.withCredentials = true) it does, and the rules get stricter:

If you use bearer tokens in an Authorization header instead of cookies, you don't need Access-Control-Allow-Credentials at all. Authorization is an ordinary request header that must be listed in Access-Control-Allow-Headers.

Matching origins safely

A static Set of allowed origins is the safest policy. If you must allow a pattern, such as every subdomain, parse the origin instead of matching strings. Each naive check below accepts origins an attacker can register:

import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Locale;

public class OriginMatch {
    // Wrong: all of these accept origins an attacker can register
    static boolean naiveEndsWith(String origin) { return origin.endsWith("example.com"); }
    static boolean naiveContains(String origin) { return origin.contains("app.example.com"); }
    static boolean naiveRegex(String origin)    { return origin.matches("https://.*.example.com"); }

    // Right: parse the origin, then compare scheme, host and port exactly
    static boolean allowed(String origin) {
        if (origin == null || origin.equals("null")) return false;
        try {
            URI u = new URI(origin);
            if (!"https".equals(u.getScheme()) || u.getHost() == null) return false;
            if (u.getRawPath() != null && !u.getRawPath().isEmpty()) return false;
            if (u.getRawUserInfo() != null || u.getRawQuery() != null) return false;
            if (u.getPort() != -1 && u.getPort() != 443) return false;
            String host = u.getHost().toLowerCase(Locale.ROOT);
            return host.equals("example.com") || host.endsWith(".example.com");
        } catch (URISyntaxException e) {
            return false;
        }
    }

    public static void main(String[] args) {
        List<String> origins = List.of(
            "https://app.example.com",
            "https://admin.example.com",
            "https://evilexample.com",
            "https://app.example.com.evil.net",
            "https://appxexample.com",
            "http://app.example.com",
            "https://app.example.com:8443",
            "null");
        System.out.printf("%-34s %-9s %-9s %-9s %s%n", "origin", "endsWith", "contains", "regex", "parsed");
        for (String o : origins) {
            System.out.printf("%-34s %-9s %-9s %-9s %s%n", o,
                naiveEndsWith(o), naiveContains(o), naiveRegex(o), allowed(o));
        }
    }
}

Output:

origin                             endsWith  contains  regex     parsed
https://app.example.com            true      true      true      true
https://admin.example.com          true      false     true      true
https://evilexample.com            true      false     true      false
https://app.example.com.evil.net   false     true      false     false
https://appxexample.com            true      false     true      false
http://app.example.com             true      true      false     false
https://app.example.com:8443       false     true      false     false
null                               false     false     false     false

The regex fails because . matches any character, so https://evilexample.com passes. contains fails because anyone can register app.example.com.evil.net. endsWith("example.com") without the leading dot accepts evilexample.com. The parsed version also rejects plain http, which a network attacker could inject.

Some other mistakes to avoid:

CORS in Spring

Spring has CORS support built in. CorsConfiguration holds a policy, and its check* methods are what Spring's DefaultCorsProcessor uses to decide each request. You can call them directly to see how a policy behaves:

import java.util.List;
import org.springframework.http.HttpMethod;
import org.springframework.web.cors.CorsConfiguration;

public class SpringCors {
    public static void main(String[] args) {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOriginPatterns(List.of("https://*.example.com", "http://localhost:[*]"));
        config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
        config.setAllowedHeaders(List.of("Content-Type", "Authorization"));
        config.setExposedHeaders(List.of("X-Request-Id"));
        config.setAllowCredentials(true);
        config.setMaxAge(600L);

        for (String origin : List.of("https://app.example.com", "http://localhost:5173",
                "https://evilexample.com", "http://app.example.com")) {
            System.out.printf("%-26s -> %s%n", origin, config.checkOrigin(origin));
        }
        System.out.println("PATCH   -> " + config.checkHttpMethod(HttpMethod.PATCH));
        System.out.println("PUT     -> " + config.checkHttpMethod(HttpMethod.PUT));
        System.out.println("headers -> " + config.checkHeaders(List.of("authorization", "x-debug")));

        // Combining "*" with credentials is rejected when Spring processes a request
        CorsConfiguration bad = new CorsConfiguration();
        bad.addAllowedOrigin("*");
        bad.setAllowCredentials(true);
        try {
            bad.validateAllowCredentials();
        } catch (IllegalArgumentException e) {
            System.out.println("error: " + e.getMessage());
        }
    }
}

Output (with spring-web 7.0.9):

https://app.example.com    -> https://app.example.com
http://localhost:5173      -> http://localhost:5173
https://evilexample.com    -> null
http://app.example.com     -> null
PATCH   -> null
PUT     -> [GET, POST, PUT, DELETE]
headers -> [authorization]
error: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.

allowedOriginPatterns supports * in the host and [*] or a list of ports, and Spring checks it properly: https://*.example.com doesn't match https://evilexample.com. checkOrigin returns the value to put in Access-Control-Allow-Origin, or null when the origin isn't allowed. checkHeaders returns only the allowed headers. Since x-debug is missing from it, the preflight fails.

In a Spring MVC application, configure CORS globally with a WebMvcConfigurer:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
            .allowedOrigins("https://app.example.com", "http://localhost:5173")
            .allowedMethods("GET", "POST", "PUT", "DELETE")
            .allowedHeaders("Content-Type", "Authorization")
            .exposedHeaders("X-Request-Id")
            .allowCredentials(true)
            .maxAge(600);
    }
}

Or per controller or method with @CrossOrigin:

import java.util.Map;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin(origins = "https://app.example.com", maxAge = 600)
public class ProfileController {
    @GetMapping("/api/profile")
    public Map<String, String> profile() {
        return Map.of("user", "alice");
    }
}

Both handle preflights automatically, add Vary headers and leave requests without an Origin alone. In Spring Boot, WebConfig is picked up as long as it's in a scanned package. If you use Spring Security, also call http.cors(Customizer.withDefaults()) in the SecurityFilterChain. Otherwise the security filters run first and reject preflights with 401. In WebFlux the equivalents are WebFluxConfigurer.addCorsMappings and CorsWebFilter.

Outside Spring, servlet containers have their own filters (Tomcat's org.apache.catalina.filters.CorsFilter, Jetty's CrossOriginHandler), and Javalin, Helidon and Micronaut have CORS plugins. Under the hood they all do what the HttpServer filter above does.

Debugging CORS errors

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents