What you'll learn: By the end of this lesson you will be able to configure CORS in a Spring MVC server with
addCorsMappings,@CrossOriginor aCorsFilter, say what the server must answer to a preflight and to the real request, set credentials and origins without opening the API to every site, and explain why an authentication filter placed before CORS makes a working API look broken in the browser.
A club has a guest list at the door. The doorman does not decide whether you may enter; he only tells the person at the desk upstairs whether this visitor was named. If he answers "no list here", the desk sends the visitor away even though the club was happy to serve. CORS on the server is that guest list, and the browser is the desk.
The front-end lessons The Same-Origin Policy and CORS and CORS in Practice: Preflights, Credentials and Debugging explain what the browser checks. This lesson is the server's half: what a Spring application sends back, where the configuration goes, and what breaks when another layer answers first. The transport underneath is in HTTP/1.1, HTTP/2 and HTTP/3 on the Server.
Verified with the Spring Framework reference (the 7.1.0 page; the lab runs Spring Framework 7.0.10 from Spring Boot 4.1.2), the Spring Security reference and MDN, on 2026-12-01.
The core idea
The server never enforces CORS against the caller. It answers the browser's question, "may this origin read this response?", with headers; a missing or wrong answer makes the browser withhold the response. A request with no Origin header, such as one from curl, is not a CORS request at all.
Three illustrations run through it: a minimal example (the lab), a realistic example (an admin page on another origin) and a failure example (an authentication filter that rejects the preflight).
What Spring answers
In Spring MVC, "Preflight requests are handled directly, while simple and actual CORS requests are intercepted, validated, and have required CORS response headers set", by the handler mapping once it has found the handler. Your controller method never sees the preflight. If no configuration matches, "no CORS headers are added" and browsers reject the request.
Figure 1. The layers a browser request meets. How to read this: filters run before Spring MVC, so a CorsFilter at the front answers a preflight before the authentication filter sees it.
Three ways to configure it
@CrossOriginon a controller or method. By default it allows all origins, all headers and all methods the method is mapped to, withmaxAgeof 30 minutes.addCorsMappingson aWebMvcConfigurer: one global rule per path pattern, defaulting to all origins, all headers andGET,HEADandPOST.CorsFilter, a servlet filter built from aCorsConfigurationSource.
The first two combine: "generally additive", except that for allowCredentials and maxAge "the local overrides the global value". Spring Security has its own CORS integration.
request with no token?"} B -->|"yes"| C["CorsFilter first in the chain
(or Spring Security's CORS support)"] B -->|"no"| D{"One policy for many endpoints?"} D -->|"yes"| E["addCorsMappings"] D -->|"no"| F["@CrossOrigin on the handler"]
Figure 2. Where to put the rule. How to read this: start with the filters ahead of Spring MVC; they decide whether a preflight reaches it.
The defaults are open, so a real configuration names what it allows. The lab's global rule, used for the rest of the lesson:
registry.addMapping("/v1/**")
.allowedOrigins("https://shop.example")
.allowedMethods("GET", "PUT", "DELETE")
.allowedHeaders("authorization", "content-type")
.exposedHeaders("X-Total-Count")
.allowCredentials(true)
.maxAge(600);
Answering the preflight and the real request
A PUT with a JSON body and an Authorization header makes the browser send two requests, and both responses need headers. The preflight response must say the method and headers are acceptable and, for a credentialed request, "must specify Access-Control-Allow-Credentials: true" (MDN). The real response needs its own Access-Control-Allow-Origin.
Origin, Access-Control-Request-Method: PUT S-->>B: 200, Allow-Origin, Allow-Credentials, Allow-Headers, Allow-Methods, Max-Age Note over S,C: the controller is not called B->>S: PUT /v1/orders/42
Origin, Authorization S->>C: handle C-->>S: updated 42 S-->>B: 200, Allow-Origin, Allow-Credentials
Figure 3. The two requests of the allowlist configuration. How to read this: the first answer decides whether the second request is sent. The controller runs only for the second.
Build it: five configurations through MockMvc
This is the minimal example. MockMvc builds each request in memory, so the lab shows what the server answers, not what a browser decides. It uses Spring MVC with @EnableWebMvc, not a started Spring Boot context; no Docker, no network.
Goal. See an allowed preflight and real request, the rejections, the over-broad pattern and the filter-order failure.
Setup. From examples/spring-labs:
cd examples/spring-labs && ./gradlew :labs:cors-server-config:test
Ten tests assert the claims below and one compares the full report with examples/spring-labs/golden/cors-server-config.txt. The code is under examples/spring-labs/labs/cors-server-config/src/main/java/buildingai/labs/cors/.
Expected output, captured from a real run (Java 25.0.3, Spring Framework 7.0.10, Spring Boot 4.1.2, 2026-12-01), scenarios 3 and 4, the allowlist configuration:
--- 3. Preflight from the allowed origin
request : OPTIONS /v1/orders/42 [Access-Control-Request-Headers: authorization,content-type; Access-Control-Request-Method: PUT; Origin: https://shop.example]
response: 200
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: authorization, content-type
Access-Control-Allow-Methods: GET,PUT,DELETE
Access-Control-Allow-Origin: https://shop.example
Access-Control-Expose-Headers: X-Total-Count
Access-Control-Max-Age: 600
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
--- 4. The real PUT after the preflight
request : PUT /v1/orders/42 [Authorization: Bearer illustrative-token; Origin: https://shop.example]
response: 200 body: updated 42
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: https://shop.example
Access-Control-Expose-Headers: X-Total-Count
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
The first response is a 200 with the one exact origin, credentials true, and the requested headers and method listed. Vary tells a shared cache that the answer depends on Origin and the request headers. Max-Age: 600 is the lab's value; an unset value came back as 1800 seconds (scenario 12), the reference's "30 minutes", and browsers apply their own limits.
What a rejection looks like
Expected output, captured from a real run (same run), scenarios 6 to 8:
--- 6. Preflight from another origin
request : OPTIONS /v1/orders/42 [Access-Control-Request-Headers: authorization,content-type; Access-Control-Request-Method: PUT; Origin: https://evil.example]
response: 403 body: Invalid CORS request
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
--- 7. Preflight asking for a header that is not listed
request : OPTIONS /v1/orders/42 [Access-Control-Request-Headers: authorization,x-debug; Access-Control-Request-Method: PUT; Origin: https://shop.example]
response: 200
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: authorization
Access-Control-Allow-Methods: GET,PUT,DELETE
Access-Control-Allow-Origin: https://shop.example
Access-Control-Expose-Headers: X-Total-Count
Access-Control-Max-Age: 600
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
--- 8. Preflight asking for a method that is not listed
request : OPTIONS /v1/orders/42 [Access-Control-Request-Headers: authorization; Access-Control-Request-Method: PATCH; Origin: https://shop.example]
response: 403 body: Invalid CORS request
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
An unlisted origin and an unlisted method both get 403 with the body Invalid CORS request and no Access-Control- headers. The header case is subtler. Asking for authorization and x-debug, where only authorization is configured, returned 200 listing only authorization. The server did not refuse; it listed what it allows, the browser finds x-debug missing and fails the preflight. A 200 does not prove the browser will proceed.
A request with no Origin header (scenario 9) gets no CORS headers, and a handler-level @CrossOrigin(origins = "https://partner.example") adds to the global origins rather than replacing them (scenarios 10 and 11).
Credentials and origins
The wildcard and credentials rules are the browser's, in the front-end lesson; the server's job is the origin policy. With credentials on, "Wildcards are not authorized in allowOrigins, but alternatively the allowOriginPatterns property may be used to match to a dynamic set of origins", and the reference warns that credentials raise the attack surface by exposing cookies and CSRF tokens.
Expected output, captured from a real run (same run), scenario 13 and the start of the filter scenarios:
== Mode star-with-credentials: allowedOrigins("*") plus allowCredentials(true)
--- 13. Any request that reaches the CORS check (context refresh succeeds)
failure : 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.
== Mode filter: the allowlist as a CorsFilter, with a bearer-token filter
--- 14. Auth filter first: the preflight
request : OPTIONS /v1/orders/42 [Access-Control-Request-Headers: authorization,content-type; Access-Control-Request-Method: PUT; Origin: https://shop.example]
response: 401 body: token required
(no CORS headers)
--- 15. Auth filter first: the real PUT without a token
request : PUT /v1/orders/42 [Origin: https://shop.example]
response: 401 body: token required
(no CORS headers)
allowedOrigins("*") with allowCredentials(true) builds without complaint and fails on the first request that reaches the CORS check, with a message that names the fix. The tempting fix, allowedOriginPatterns("*"), is worse: in scenario 12 a preflight from https://evil.example came back with Access-Control-Allow-Origin: https://evil.example and Access-Control-Allow-Credentials: true. The server echoed whichever origin asked. For a credentialed API that is no allowlist at all. Keep a finite list from configuration and test an origin that must be refused.
The preflight has no token
Scenarios 14 and 15 above are the failure. A preflight carries no credentials, so a filter that demands an Authorization header rejects it with 401 and no CORS headers. The Spring Security reference says "CORS must be processed before Spring Security, because the pre-flight request does not contain any cookies", and calls the CorsFilter "the easiest way to ensure that CORS is handled first".
Figure 4. Filter order decides the outcome. How to read this: the top exchange is scenario 14, the bottom one scenario 16 with the order swapped.
A second effect: with the auth filter first, a 401 carries no CORS headers (scenario 15), so the page cannot read it; with the CorsFilter first it does (scenario 17), and the page can show a login prompt.
Trade-offs
| Choice | Gain | Cost | Wrong when |
|---|---|---|---|
@CrossOrigin |
Rule beside the code | Scatters, and defaults are open | Many endpoints share one policy |
addCorsMappings |
One reviewable policy | Reached only after earlier filters | A filter rejects preflights first |
CorsFilter first |
Answers before authentication | A second place for rules | You also keep CORS in MVC and they drift |
In practice: ShopStream's admin page on a second origin
This is the realistic example, an educational scenario on ShopStream; nothing in it describes a real company.
This is a realistic scenario, not a case history.
The situation
ShopStream's store-admin page at https://admin.shop.example calls the orders API at https://api.shop.example with a bearer token and JSON bodies. The shopper site at https://shop.example reads the product list.
Starting architecture
A gateway authenticates every request and forwards it to the orders service, which has no CORS configuration. The first PUT fails with a preflight error; curl with a token works.
Options considered
| Option | Behaviour | Problem |
|---|---|---|
A. Patterns * with credentials |
The error disappears | Any site can read credentialed answers |
| B. Named origins in the service only | Correct policy | The gateway answers the preflight with 401 |
C. Named origins in a CorsFilter before authentication |
Correct, preflight answered | One more filter to own |
The decision
Option C: a CorsFilter first in the chain, origins read from configuration, the exact methods and headers the clients use, credentials only where cookies are used. The shopper origin gets read-only methods.
Rollout and verification
Add the filter in staging with tests like the lab's (allowed origin, refused origin, token-less preflight), then check the browser's network tab against the deployed gateway, which has rules this lab does not model.
The 2 a.m. failure
After a gateway change every admin call shows a CORS error; the service did not change. First checks: the status of the OPTIONS request, whether the gateway now authenticates before the filter, and whether two layers add Access-Control-Allow-Origin. Mitigate by restoring the preflight path; fix lastingly with a test that sends a token-less preflight to the deployed endpoint.
Architect's notes
- Own CORS in one layer and test a refused origin on every release.
- CORS is not access control.
curlignores it, so the server still authenticates every request.
Common mistakes
- Authentication before CORS, so the preflight is rejected.
allowedOriginPatterns("*")with credentials to silence an error.- Trusting a 200 preflight. The browser still compares each requested header.
- Two layers adding CORS headers.
Key takeaways
- The server answers the browser's question with headers; it does not enforce CORS on callers.
- Spring handles a preflight before your controller; the real response needs its own headers.
- Name origins, methods and headers; keep credentials off unless cookies are used.
- Filters ahead of the CORS handling, especially authentication, can reject the token-less preflight.
Practice exercises
Exercise 1 (20 min). Run the lab and list the status and headers of scenarios 6, 7 and 8.
Exercise 2 (45 min). Change the allowlist to two origins and add a test that a third gets 403.
Related reading
- The Same-Origin Policy and CORS and CORS in Practice: Preflights, Credentials and Debugging: the browser's half.
- HTTP/1.1, HTTP/2 and HTTP/3 on the Server: the protocol under the headers.
- Forward and Reverse Proxies: the layer that often adds or strips these headers.
Official documentation
- Spring Framework, CORS: handler mapping,
@CrossOrigin, global configuration,CorsFilter, credentials. - Spring Security, CORS: why CORS comes before security, and the
CorsFilterapproach. - MDN, Cross-Origin Resource Sharing (CORS): preflight response, credentials,
Vary: OriginandAccess-Control-Max-Age.