Skip to lesson

Common CORS mistakes

A teammate "fixes" a CORS error by allowing every origin, and the error disappears. The app now works, and any website can read signed-in customers' data. Which CORS fixes are safe, and which are traps?

Allowing * with credentials

Credentials mode means the browser sends cookies or HTTP authentication with a cross-origin request: fetch(url, { credentials: 'include' }). The CORS standard forbids answering such a request with Access-Control-Allow-Origin: *.

The cors-lab setup below allows * and credentials together. Watch what Spring and Chrome each do with it.

Example 1 · * with credentials: Spring refuses, and so does Chrome

Runs in: the cors-lab Spring Boot project, profile star-credentials (and profile star for the Chrome run)

Java
// cors-lab, profile "star-credentials"@BeanCorsConfigurationSource corsConfigurationSource() {    CorsConfiguration config = new CorsConfiguration();    config.setAllowedOrigins(List.of("*"));    config.setAllowedMethods(List.of("*"));    config.setAllowedHeaders(List.of("*"));    config.setAllowCredentials(true);    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();    source.registerCorsConfiguration("/api/**", config);    return source;}
Sample output (Spring Security's cache and X- headers left out)
$ curl -i http://localhost:8080/api/v1/products -H "Origin: http://localhost:3000"
HTTP/1.1 500 
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 08:05:33 GMT
Connection: close

{"timestamp":"2026-10-16T08:05:33.844Z","status":500,"error":"Internal Server Error","path":"/api/v1/products"}

Server log:
java.lang.IllegalArgumentException: 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.
	at org.springframework.web.cors.CorsConfiguration.validateAllowCredentials(CorsConfiguration.java:552) ~[spring-web-7.0.9.jar!/:7.0.9]

Chrome, a server that really sends "*" (profile "star") and fetch(..., { credentials: 'include' }):
Access to fetch at 'http://localhost:8080/api/v1/products' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

What this code does

  • Spring checks the combination on the first CORS request and throws, so every call from a browser page gets a 500; the log line tells you exactly what to change.
  • The last line comes from a second profile that sends * without Spring's check failing, called with credentials: 'include'. The browser refuses it on its own, so this mistake can never work.

A wildcard plus cookies would let every website on the internet read every user's signed-in data. Spring checks this for you: setAllowedOrigins(List.of("*")) together with setAllowCredentials(true) makes CorsConfiguration throw IllegalArgumentException on every CORS request, so the API answers 500. The browser has its own check as well.

The fix is never "make the wildcard work". Decide whether you need cookies at all (ShopLite does not, its token travels in a header), and if you do, list the exact origins.

Find the bug

Find the credentials bug

Both setups fail in the browser. Click the line that causes it.

Every CORS request to this API answers 500. Which line is the problem?

Round 1 of 2
Interview angle: "Can I use Access-Control-Allow-Origin: * with cookies?" No. The browser refuses it, and Spring refuses to even build that answer.

Reflecting any Origin back

Reflecting the Origin means the server copies whatever Origin the request has into Access-Control-Allow-Origin. With credentials on, every website then gets a yes and can read signed-in data.

The cors-lab profile below looks like a fix for the error above. Check what an unknown site gets back.

Example 2 · Reflecting any origin: evil.example gets a yes

Runs in: the cors-lab Spring Boot project, profile reflect-any

Java
@BeanCorsConfigurationSource corsConfigurationSource() {    CorsConfiguration config = new CorsConfiguration();    config.setAllowedOriginPatterns(List.of("*"));    config.setAllowedMethods(List.of("*"));    config.setAllowedHeaders(List.of("*"));    config.setAllowCredentials(true);    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();    source.registerCorsConfiguration("/api/**", config);    return source;}
/* test it:curl -i -X OPTIONS http://localhost:8080/api/v1/me/orders \  -H "Origin: https://evil.example" \  -H "Access-Control-Request-Method: GET" \  -H "Access-Control-Request-Headers: authorization"*/
Sample output (Spring Security's Cache-Control, Pragma, Expires and X- headers left out; your Date differs)
HTTP/1.1 200 
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Access-Control-Allow-Origin: https://evil.example
Access-Control-Allow-Methods: GET
Access-Control-Allow-Headers: authorization
Access-Control-Allow-Credentials: true
Content-Length: 0
Date: Fri, 16 Oct 2026 08:05:32 GMT

What this code does

  • The preflight from https://evil.example got 200 with its own origin echoed back and Access-Control-Allow-Credentials: true. A browser would now send the user's cookies and let that page read the answer.
  • The fix is the ShopLite setup: setAllowedOrigins(properties.allowedOrigins()) with exact origins, and credentials only when cookies are really needed.

Developers often reach for reflection to silence the wildcard error, as a hand-made filter (response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"))) or as setAllowedOriginPatterns(List.of("*")) with credentials. Spring accepts the pattern version, because a pattern answers with the concrete origin, not *.

With credentials on, the browser sends the victim's cookies to the API and the page of https://evil.example reads the answer: orders, addresses, phone numbers. That undoes the same-origin policy for your API, and it is a classic finding in security audits. Patterns are fine when they are narrow, such as https://*.shoplite.example; never use *, and never a pattern that also matches look-alike domains.

Fix the error

Close the hole

An unknown site must not get a yes. Pick the replacement for the highlighted line.

Round 1 of 2

The pattern matches every origin.

CorsConfiguration config = new CorsConfiguration();
config.setAllowedOriginPatterns(List.of("*"));
config.setAllowCredentials(true);

Error

Origin: https://evil.example  ->
Access-Control-Allow-Origin: https://evil.example
Access-Control-Allow-Credentials: true

@CrossOrigin and the security chain configured differently

@CrossOrigin adds CORS rules to one controller or method through Spring MVC. In an app with Spring Security it runs after the security filters, so it cannot answer a preflight for a protected URL.

The cors-lab controller below carries the annotation, but its security chain has no .cors(...).

Example 3 · @CrossOrigin alone on a protected endpoint

Runs in: the cors-lab Spring Boot project, profile crossorigin (security chain without .cors)

Java
// cors-lab, profile "crossorigin": CORS only on the controller, chain without .cors(...)@RestController@CrossOrigin(origins = "http://localhost:3000")class WishlistController {    @GetMapping("/api/v1/me/wishlist")    List<String> wishlist() {        return List.of("iPhone 15 128GB");    }}
Sample output
$ curl -i -X OPTIONS http://localhost:8080/api/v1/me/wishlist -H "Origin: http://localhost:3000" \
    -H "Access-Control-Request-Method: GET" -H "Access-Control-Request-Headers: authorization"
HTTP/1.1 401 
WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 08:05:32 GMT

{"timestamp":"2026-10-16T08:05:32.624Z","status":401,"error":"Unauthorized","path":"/api/v1/me/wishlist"}

Chrome console:
Access to fetch at 'http://localhost:8080/api/v1/me/wishlist' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

What this code does

  • The annotation is correct, but the preflight stopped at Spring Security with 401 and the HTTP Basic challenge. No CORS header was ever added.
  • In ShopLite the same mistake gives the 401 problem body instead of Basic's challenge; the browser message is identical. Moving the rules into CorsConfig and calling .cors(...) fixes it for every controller at once.

The preflight gets 401, and the browser blocks the call. Teams then add more annotations, an OPTIONS permit-all rule, or a second CorsConfigurationSource, and end up with CORS rules in three places that disagree. The symptoms are confusing: one endpoint works and its neighbour does not; dev works but prod does not, because someone updated only one list.

Keep one place for CORS: the CorsConfigurationSource bean used by http.cors(...), with origins from configuration. Remove @CrossOrigin and addCorsMappings once that is in place.

Small mistakes with big symptoms

The next run shows how Chrome reports an origin typo and a header the server does not allow.

Example 4 · Origin typos and header mistakes, as Chrome reports them

Runs in: a terminal (java WrongOriginServer.java) and a page on http://localhost:3000 in Chrome

WrongOriginServer.javaJava
import com.sun.net.httpserver.HttpServer;import java.net.InetSocketAddress;import java.nio.charset.StandardCharsets;
// Sends a WRONG Access-Control-Allow-Origin on purpose, to see the browser's exact-match rulepublic class WrongOriginServer {    public static void main(String[] args) throws Exception {        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 9001), 0);        server.createContext("/", ex -> {            byte[] body = "[\"hello\"]".getBytes(StandardCharsets.UTF_8);            String allow = ex.getRequestURI().getPath().equals("/slash")                    ? "http://localhost:3000/"      // trailing slash typo                    : "http://127.0.0.1:3000";      // right computer, wrong host name            ex.getResponseHeaders().add("Access-Control-Allow-Origin", allow);            ex.getResponseHeaders().add("Content-Type", "application/json");            ex.sendResponseHeaders(200, body.length);            ex.getResponseBody().write(body);            ex.close();        });        server.start();    }}
Chrome console
fetch('http://localhost:9001/slash') from http://localhost:3000:
Access to fetch at 'http://localhost:9001/slash' from origin 'http://localhost:3000' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:3000/' that is not equal to the supplied origin. Have the server send the header with a valid value.

fetch('http://localhost:9001/ip') from http://localhost:3000:
Access to fetch at 'http://localhost:9001/ip' from origin 'http://localhost:3000' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'http://127.0.0.1:3000' that is not equal to the supplied origin. Have the server send the header with a valid value.

fetch with an X-Trace-Id header to an API that allows only Authorization and Content-Type:
Access to fetch at 'http://localhost:8080/api/v1/products' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field x-trace-id is not allowed by Access-Control-Allow-Headers in preflight response.

What this code does

  • The JDK server sends a wrong Access-Control-Allow-Origin on purpose. A trailing slash and 127.0.0.1 both fail the exact comparison, and Chrome prints the value it received, which makes these typos easy to spot.
  • The third message is from the ShopLite-style setup: the page added X-Trace-Id, which is not in the allowed headers. Either add it to setAllowedHeaders or stop sending it.

Four everyday mistakes end in a CORS error, each with its own symptom:

  • Preflight blocked by security: the message mentions preflight request and No 'Access-Control-Allow-Origin' header.
  • A header the page sends but the server does not allow: the message names it, for example Request header field x-trace-id is not allowed.
  • A missing exposed header: no error at all, just null from response.headers.get('Location'); check Access-Control-Expose-Headers.
  • An origin typo: the browser compares Access-Control-Allow-Origin with its own origin letter by letter, so a trailing slash, https instead of http, a missing port or 127.0.0.1 instead of localhost all fail.

Spring trims a trailing slash in setAllowedOrigins for you, but a hand-written header, a proxy rule or another framework may not, which is why ShopLite also rejects such values at startup. Read the console message first, and compare the page origin and the allowed origin letter by letter.

CORS does not protect the server

The two curl calls below use a customer token: one with no Origin header, one from a foreign origin.

Example 5 · CORS does not stop curl

Runs in: a terminal, with the ShopLite API (dev profile) on port 8080 and TOKEN holding a customer's access token

Terminal
# An attacker with a stolen token does not need a browser at allcurl -s "http://localhost:8080/api/v1/me/orders?size=10" -H "Authorization: Bearer $TOKEN"# Spring refuses an unknown Origin...curl -i "http://localhost:8080/api/v1/me/orders?size=10" -H "Authorization: Bearer $TOKEN" \  -H "Origin: https://evil.example"
Sample output (Spring Security's Cache-Control, Pragma, Expires and X- headers left out; your Date differs)
{"content":[{"id":10,"customerId":1,"status":"DELIVERED","orderedAt":"2026-08-30T12:25:00+05:30","total":4398.00},{"id":3,"customerId":1,"status":"DELIVERED","orderedAt":"2026-07-18T13:05:00+05:30","total":43839.00},{"id":1,"customerId":1,"status":"DELIVERED","orderedAt":"2026-07-02T10:12:00+05:30","total":21097.00}],"page":0,"size":10,"totalElements":3,"totalPages":1}

HTTP/1.1 403 
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 08:05:16 GMT

Invalid CORS request

What this code does

  • Without an Origin header, the request is not a CORS request at all: the API checks only the token and returns the orders. That is the correct behaviour; the token is what protects this data.
  • With a foreign Origin, Spring answers 403 Invalid CORS request. An attacker simply leaves the header out, so this 403 is a browser convenience, not a lock.

CORS protects users: it stops other websites from reading data through a user's browser. It does not protect the API. curl, Postman, Python scripts and attackers' tools ignore CORS completely, and they can send any Origin header they like, or none.

Spring does answer 403 Invalid CORS request to an unknown Origin, which looks like protection, but leave the header out and the same request goes straight through. Who may call what is decided by authentication, roles and owner checks, the earlier modules of this section; CORS only decides which browser pages may read the answers.

Interview angle: "We restricted CORS to our domain, so the API is safe?" No. CORS is a browser feature; the API still needs authentication, authorization and rate limits.

Next step

Check your understanding

12 quick questions