CORS
A browser keeps a page of https://shop.example from reading the answers of https://api.example, unless the API allows it with Access-Control-Allow-... headers. This is CORS (Cross-Origin Resource Sharing). The starter answers it from the rules you declare: @CrossOrigin on a controller or method, addCorsMappings in a WebMvcConfigurer, or a CorsConfigurationSource bean named corsConfigurationSource.
Why
An origin is a scheme, a host and a port: https://shop.example and https://api.example are two origins, and so are http://localhost:3000 and http://localhost:8080. When a page calls another origin with fetch, the browser:
- for most requests, first sends an
OPTIONSpre-flight withOrigin,Access-Control-Request-Methodand oftenAccess-Control-Request-Headers, and asks whether the call is allowed; - sends the actual request with an
Originheader; - lets the page read the answer only when it carries an
Access-Control-Allow-Originthat matches.
You need CORS rules when a front end on another origin calls your API: a Flutter web app served by a CDN, a site on another domain, a development server on another port. An API used only by its own pages, or only by programs (other servers, mobile apps), needs none: CORS binds browsers only.
Example
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';
// On a controller: the shop's pages may call every method of it.
@RestController()
@RequestMapping('/api/books')
@CrossOrigin(origins: ['https://shop.example'], maxAge: 3600)
class BookController {
@GetMapping()
List<String> list() => ['Dune'];
// The method adds to the class: PUT from the shop, with its cookies.
@PutMapping('/{isbn}')
@CrossOrigin(allowCredentials: true, exposedHeaders: ['Location'])
void update(@PathVariable() String isbn) {}
}
// For many paths at once: a WebMvcConfigurer.
@Configuration()
class WebConfig with WebMvcConfigurer {
@override
void addCorsMappings(CorsRegistry registry) {
registry
.addMapping('/api/**')
.allowedOriginPatterns(['https://*.shop.example', 'http://localhost:[*]'])
.allowedMethods(['GET', 'HEAD', 'POST', 'PUT', 'DELETE'])
.allowCredentials(true);
registry.addMapping('/public/**'); // any origin, GET, HEAD, POST
}
}
Or the rules as a bean, which then alone decides for the paths it covers:
@Configuration()
class CorsConfig {
@Bean()
CorsConfigurationSource corsConfigurationSource() =>
UrlBasedCorsConfigurationSource()
..registerCorsConfiguration(
'/api/**',
CorsConfiguration(
allowedOriginPatterns: ['https://*.shop.example'],
allowCredentials: true,
)..applyPermitDefaultValues(), // GET, HEAD, POST, every header, 30 min
);
}
A pre-flight and its answer:
OPTIONS /api/books/42
Origin: https://eu.shop.example
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: content-type
200 OK
Access-Control-Allow-Origin: https://eu.shop.example
Access-Control-Allow-Methods: GET,HEAD,POST,PUT,DELETE
Access-Control-Allow-Headers: content-type
Access-Control-Expose-Headers: Location
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 3600
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
The methods come from the global mapping and the handler together, the origin from the global pattern, the max age from the class's @CrossOrigin, credentials and the exposed header from the method's.
The three ways to declare rules
| Way | Scope | Defaults for what it leaves out | Combined with |
|---|---|---|---|
@CrossOrigin on a class or method |
That controller's handlers | Every origin, the method the handler is mapped to, every header, 30 minutes | The global mappings, the class with the method |
WebMvcConfigurer.addCorsMappings |
Path patterns: controllers, the static resources, a 404 |
Every origin, GET, HEAD and POST, every header, 30 minutes |
Each handler's @CrossOrigin |
A CorsConfigurationSource bean named corsConfigurationSource |
Whatever it returns a configuration for | None: a configuration is used as it is | Nothing: where it has rules, they alone apply |
@CrossOrigin
| Attribute | Type | Default | Meaning |
|---|---|---|---|
origins |
List<String> |
[]: any origin, when originPatterns is empty too |
Whole origins allowed (https://shop.example), compared without case. * allows any. |
originPatterns |
List<String> |
[] |
Origin patterns (https://*.shop.example, http://localhost:[*]). See "Origins and patterns" below. |
methods |
List<String> |
[]: the method the handler is mapped to |
Methods allowed (PUT, DELETE, *), for pre-flights and actual requests. |
allowedHeaders |
List<String> |
[]: every header |
Request headers a pre-flight may ask for, compared without case. * allows any. |
exposedHeaders |
List<String> |
[]: none |
Response headers, beyond the simple ones, that the page's script may read (Location, X-Total-Count). |
allowCredentials |
bool? |
null: no |
Whether the browser may send cookies and other credentials, and let the page read the answer. |
allowPrivateNetwork |
bool? |
null: no |
Whether a page of a public site may call this server on a private network (Chrome's Private Network Access). |
maxAge |
int? |
null: 1800 |
How long, in seconds, the browser may reuse a pre-flight answer. |
Rules:
- On the class for all its handlers, on a method for that one. When both carry it, their lists are merged and the method's
allowCredentials,allowPrivateNetworkandmaxAgewin. - Without
methods, the method the handler is mapped to is allowed, as in Spring:DELETEfor a@DeleteMapping,GETfor a@GetMapping. NotHEAD: a cross-originHEADto aGEThandler is refused. Writemethods: ['GET', 'HEAD']when pages send it. allowCredentials: trueorallowPrivateNetwork: truewithoutoriginsororiginPatterns(so with every origin) stops the startup, as in Spring:BookController.update: @CrossOrigin(allowCredentials: true) needs origins or originPatterns (all origins, "*", cannot be allowed with credentials). The same fororigins: ['*']. See Startup checks.
WebMvcConfigurer.addCorsMappings
registry.addMapping(pattern) enables CORS for the paths matching the pattern and returns a CorsRegistration:
CorsRegistration method |
Default when not called | Meaning |
|---|---|---|
allowedOrigins(List<String> origins) |
any origin (when no pattern is set either) | Adds whole origins. |
allowedOriginPatterns(List<String> patterns) |
none | Adds origin patterns. |
allowedMethods(List<String> methods) |
GET, HEAD, POST |
Adds methods. |
allowedHeaders(List<String> headers) |
every header | Adds request headers. |
exposedHeaders(List<String> headers) |
none | Adds exposed response headers. |
allowCredentials(bool allow) |
no | Credentials. With true, list origins or use patterns. |
allowPrivateNetwork(bool allow) |
no | Private Network Access. With true, list origins or use patterns. |
maxAge(Duration maxAge) |
30 minutes | The pre-flight cache. A Duration, not seconds. |
- The list methods add to what is there. Spring's replace it.
- Mappings are tried in the order they were added, across all configurers; the first pattern that matches the path wins, not the most specific one. Add specific patterns first.
- The rules apply to the controllers on those paths (combined with their
@CrossOrigin), to the static resources, and to requests no handler takes. *with credentials or a private network does not stop the startup here: every request to the mapping's paths fails with a500(aStateError), as Spring validates the configuration on each request.
The corsConfigurationSource bean
A bean of type CorsConfigurationSource named corsConfigurationSource holds the rules the security starter's CORS filter applies, as Spring Security applies the bean of that name. The router applies it the same way, so CORS behaves the same with and without the security starter:
- Where it returns a configuration for a request, that configuration alone decides. Neither
@CrossOriginnor theaddCorsMappingsrules widen it: an origin, a header or a max age they would add is not added. - Where it returns
null,@CrossOriginand the mappings apply. - The name counts, not the type. A
@Beanmethod namedcorsConfigurationSource()gives that name. A bean of the type with another name (apiCors, a library's) is ignored, as by Spring Security, and several such beans never fail the start. A bean of that name that is not aCorsConfigurationSourceis not taken for rules (the security starter fails the start on it). - A configuration you build is used as it is: empty lists allow no origin and no request header, and empty
allowedMethodsallowGETandHEAD. CallapplyPermitDefaultValues()for the permissive defaults. *with credentials or a private network fails each cross-origin request that reaches the check (a500).
UrlBasedCorsConfigurationSource picks the configuration by path pattern: registerCorsConfiguration(pattern, configuration), tried in registration order, the first match wins. Implement CorsConfigurationSource yourself (getCorsConfiguration(request)) for rules that change at run time:
// The allowed origins are the tenants' sites, which change at run time.
@Component('corsConfigurationSource')
final class TenantCors implements CorsConfigurationSource {
TenantCors(this.tenants);
final TenantService tenants;
@override
CorsConfiguration? getCorsConfiguration(ServerHttpRequest request) =>
request.path.startsWith('/api/')
? (CorsConfiguration(allowedOrigins: tenants.origins())
..applyPermitDefaultValues())
: null;
}
CorsConfiguration
| Member | Meaning |
|---|---|
CorsConfiguration({allowedOrigins, allowedOriginPatterns, allowedMethods, allowedHeaders, exposedHeaders, allowCredentials, allowPrivateNetwork, maxAge}) |
A configuration. The lists are copied and can grow later; the rest is unset by default. |
CorsConfiguration.fromAnnotation(CrossOrigin annotation, {mappedMethods}) |
The rules of an annotation: without methods, mappedMethods; then the permissive defaults. |
allowedOrigins |
Whole origins, compared without case. * allows any. Empty: none. |
allowedOriginPatterns |
Origin patterns, compared with case. |
allowedMethods |
Methods, compared with case. * allows any. Empty: GET and HEAD. |
allowedHeaders |
Request headers, compared without case. * allows any. Empty: none. |
exposedHeaders |
Access-Control-Expose-Headers. |
allowCredentials |
Access-Control-Allow-Credentials: true. null and false mean no. |
allowPrivateNetwork |
Access-Control-Allow-Private-Network: true for a pre-flight that asks for it. null and false mean no. |
maxAge |
Access-Control-Max-Age of pre-flight answers, as a Duration. null sends none. |
applyPermitDefaultValues() |
Fills what is empty: every origin (when no origin nor pattern is set), GET, HEAD and POST, every header, and a max age of 30 minutes. Returns the configuration. |
combine(CorsConfiguration? other) |
A new configuration with the rules of both; other is the more specific one. See "How rules combine" below. |
checkOrigin(String origin) |
The Access-Control-Allow-Origin value for origin, or null when it is not allowed. |
checkMethod(String method) |
The Access-Control-Allow-Methods list for method, or null when it is not allowed. |
checkHeaders(List<String> requested) |
The Access-Control-Allow-Headers list, or null when one header is not allowed. |
validateAllowCredentials(), validateAllowPrivateNetwork() |
Throw a StateError when the flag is true and allowedOrigins holds *. |
Origins and patterns
Origins are checked as Spring's CorsConfiguration checks them, by AllowedOrigins (from spring_web_dart). The WebSocket starter checks handshakes with the same class, so both accept the same origins.
origins/allowedOriginsare whole origins, compared without case:https://shop.examplematcheshttps://SHOP.example.*allows any origin, and the answer is thenAccess-Control-Allow-Origin: *.originPatterns/allowedOriginPatternsare compared with case.*matches any text, as Spring's.*:https://*.shop.exampletakeshttps://eu.shop.exampleandhttps://a.b.shop.example, nothttps://shop.example;*.shop.exampletakes any scheme;*localhost*takes anylocalhostorigin;- a port list at the end takes the ports listed:
http://localhost:[3000,3001]; [*]takes any port or none:http://localhost:[*]takeshttp://localhostandhttp://localhost:5173.
- The origin is echoed back for a listed origin or a pattern, as the browser sent it. So patterns work with credentials, where
*cannot. - A value may list several, separated by commas (
'https://a.example, https://b.example'), handy when it comes from one property. The commas of a port list are not separators. - A trailing
/is ignored, in the values and in theOriginheader. - An
Originlonger than 1024 characters is never allowed (AllowedOrigins.maxOriginLength). A real origin is under 300 characters. A pattern is matched in time that grows with the origin's length, however many*it has. - An
Originwith a character other than visible US-ASCII (a space, a control character, a letter beyond ASCII) is refused with a403, and so is a pre-flight that asks for such a method or header, even where*allows any. No browser sends one, and the answer could not echo it. - As in Spring,
https://*.example.comalso takeshttps://evil.com/.example.com. No browser sends such anOrigin, and other clients can send anyOriginanyway.
Placeholders (${...}) in @CrossOrigin values are not resolved: the values are used as written. To take origins from configuration, build the rules in a WebMvcConfigurer or a bean that injects the property, and pass the comma list as one value:
@Configuration()
class WebConfig with WebMvcConfigurer {
WebConfig(@Value(r'${shop.cors.origins}') this.origins);
final String origins; // "https://a.example, https://b.example"
@override
void addCorsMappings(CorsRegistry registry) =>
registry.addMapping('/api/**').allowedOrigins([origins]);
}
How a request is checked
A request is a CORS request when it has an Origin whose scheme, host or port differs from the request's own (an Origin that does not parse counts as another origin). Only CORS requests are checked against the rules. For every request to a handler with CORS rules, the starter, like Spring's DefaultCorsProcessor:
- adds
Vary: Origin,Vary: Access-Control-Request-MethodandVary: Access-Control-Request-Headers, a CORS request or not; - refuses an
Originthat is not visible US-ASCII; - stops there, allowing the request, when it is not a CORS request;
- leaves the response as it is when it already has an
Access-Control-Allow-Origin(a filter, such as the security starter's, handled CORS); - checks the origin;
- checks the method: for a pre-flight the one in
Access-Control-Request-Method, otherwise the request's own; - for a pre-flight, checks every header of
Access-Control-Request-Headers; - writes the headers below.
A refusal is a 403 with the text Invalid CORS request, and the handler is not called.
| Header | Pre-flight | Actual request |
|---|---|---|
Access-Control-Allow-Origin |
the origin, or * |
the origin, or * |
Access-Control-Allow-Methods |
the allowed methods (with *: the method asked for) |
โ |
Access-Control-Allow-Headers |
the headers asked for, when some were | โ |
Access-Control-Expose-Headers |
when set | when set |
Access-Control-Allow-Credentials |
true, when allowed |
true, when allowed |
Access-Control-Allow-Private-Network |
true, when allowed and the pre-flight sent Access-Control-Request-Private-Network: true |
the same |
Access-Control-Max-Age |
the seconds, when set | โ |
The method is always checked
Every cross-origin request is checked with its method, the actual request too. So an allowed origin's DELETE, PUT, HEAD or OPTIONS that the rules do not list is refused with a 403 before the handler runs, even if the browser sent no pre-flight. With the security starter, this happens before the security checks.
Pre-flights
A pre-flight is an OPTIONS request with Origin and Access-Control-Request-Method. It is answered from the CORS rules, never passed to a handler or an interceptor.
| Situation | Answer |
|---|---|
| A path no handler maps | The next handler mappings; in the end a 404. A static file's pre-flight is answered from the global rules. |
| A mapped path, a handler for the announced method, with rules | 200 with the CORS headers, or 403 when they refuse it. |
| A mapped path, no handler for the announced method | The global rules alone decide: 200 or 403, never a 405, as in Spring. |
| A mapped path without any CORS rules | 200 with no CORS header and no Vary. The browser then blocks the request it announced. |
| From the server's own origin | Not a CORS request: 200, with the Vary headers when the path has rules. |
Which handler's rules? A pre-flight cannot say which Content-Type or Accept its request will send, so it is answered from the rules of the first handler of its path and announced method: the most specific pattern, then the one with the most conditions. This differs from Spring when several handlers match the pre-flight's path and method and all of them have @CrossOrigin rules: those mapped to exactly that path when there are some (GET /items producing JSON for one origin and CSV for another), else every matching pattern (/items/{id} and /items/** for /items/7). Spring then allows the pre-flight from any origin, with credentials, and leaves the check to the actual request. Here an origin that the first handler's rules do not allow gets a 403 for the pre-flight: no origin gets more than one handler's rules. Give such handlers the same CORS rules. The actual request is always checked against the rules of the handler that answers it.
Requests without rules
- On a path without CORS rules, a cross-origin request is handled as any other, without CORS headers. The browser keeps the answer from the page.
- An
OPTIONSrequest that is not a pre-flight, to a path without anOPTIONShandler, gets200withAllow. The global rules apply to it first, withOPTIONSas its method.
Vary
Every answer of a handler with CORS rules gets Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers: a CORS request or not, from an allowed origin or a refused one. A cache in between then keeps the answers to different origins apart.
- Each name is added once, next to the names already in
Vary(a filter's), in any case. - A handler's own
Vary(of aResponseEntityor anErrorResponse) adds its names to these, rather than replacing them, as Spring'sHttpEntityMethodProcessormerges them. On a handler without CORS rules it is written as it is. - Nothing is added to a
Vary: *already there. - With the security starter, its CORS filter adds the names to every request with CORS rules before the security checks, so its own
401and403answers have them too. - Answers of handlers without rules get none.
How rules combine
The rules are combined as in Spring: the global ones (the addCorsMappings mappings) first, then the class's @CrossOrigin, then the method's. The more specific side is other in combine:
- Lists that both sides set are merged. A
*on either side makes the result*. - A list that holds only the defaults of
@CrossOriginorapplyPermitDefaultValues()gives way to the other side's list: it never widens what the other side sets.@CrossOrigin()withoutoriginskeeps the global origins instead of widening them to*. - An empty list takes the other side's.
- Default origins next to patterns from the other side: the patterns alone.
allowCredentials,allowPrivateNetworkandmaxAgeof the more specific side win when they are set.@CrossOriginalways brings amaxAge(its own or 1800 seconds), so it wins over the global one.
Examples, under a global mapping /api/** with allowedOrigins(['https://shop.example']):
| On the handler | Origins | Methods |
|---|---|---|
| nothing | https://shop.example |
GET, HEAD, POST (the mapping's defaults) |
@CrossOrigin() on a @PutMapping |
https://shop.example |
PUT (the mapped method, set by the handler, replaces the mapping's defaults) |
@CrossOrigin(origins: ['https://admin.example']) |
https://shop.example, https://admin.example |
the mapped method |
With .allowedMethods(['GET', 'POST']) on the mapping, a @CrossOrigin(methods: ['PUT']) handler allows GET, POST and PUT: both sides set the list, so they are merged.
Credentials and private networks
- Credentials (cookies, HTTP authentication, client certificates) are sent cross-origin only when the page asks (
fetch(url, {credentials: 'include'})) and the answer saysAccess-Control-Allow-Credentials: truewith the exact origin. Browsers refuse*with credentials. SoallowCredentials: trueneeds listed origins or patterns:@CrossOrigin: the startup fails;- an
addCorsMappingsmapping: every request to its paths is a500; - the
corsConfigurationSourcebean: every cross-origin request it allows by*is a500.
- Private Network Access (Chrome): a page of a public site that calls a server on
localhostor an office network sends a pre-flight withAccess-Control-Request-Private-Network: true. WithallowPrivateNetwork: true, the answer addsAccess-Control-Allow-Private-Network: true. It has the same rule as credentials: never with*, or every site could reach the private network. Use it for a local helper app or an intranet server called from a public site. - A session cookie sent cross-site also needs
SameSite=NoneandSecure. See Sessions.
Behind a proxy that terminates TLS
Browsers send an Origin with every POST, PUT, PATCH and DELETE, to their own site too. When a proxy terminates TLS (or changes the host or the port), the server sees http and its own address, so the application's own pages look like another origin, and their requests are checked as cross-origin ones. Under addCorsMappings rules for /** with the defaults, a page's own PUT or DELETE is then a 403; with origins that leave out the site's own, its POST too.
Fix it in one of these ways:
- set
server.forward-headers-strategyso the request knows its real scheme, host and port from the proxy's headers (see Behind a reverse proxy); - give CORS rules only to the paths other sites call (
/api/public/**rather than/**); - list the site's own origin and every method its pages send;
- terminate TLS in the application (see SSL).
Where the rules apply
- Controllers: the handler's rules (the bean's, or the global ones combined with
@CrossOrigin). - Static resources: the global rules (
addCorsMappings, or the bean's), as Spring gives them to its resource handler mapping. See Static resources. - A
404(no handler): the global rules. - Another handler mapping (WebSocket endpoints): only the bean's rules where it has some. The
addCorsMappingsrules and@CrossOriginbelong to the controllers; a WebSocket endpoint checks theOriginof a handshake itself. See WebSocket.
DispatcherHandler.corsConfigurationFor(request) gives the rules that apply to a request, asking the handler mappings in order as the request itself would; the security starter's CORS filter uses it. Spring's counterpart is HandlerMappingIntrospector.getCorsConfiguration.
For a filter or a handler mapping of your own: isCorsRequest(request), isPreFlightRequest(request), and processCors(config, request, response, preFlight: ...), which writes the headers and returns false when the request must be refused.
In Spring (Java)
@RestController
@CrossOrigin(origins = "https://shop.example", maxAge = 3600)
class BookController { ... }
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOriginPatterns("https://*.shop.example")
.allowCredentials(true);
}
Differences that matter:
CorsRegistration's list methods add to the list; Spring's replace it. They take lists, not varargs.maxAgetakes aDuration.- The
corsConfigurationSourcebean is applied by the router too, so CORS works the same with and without the security starter. Spring MVC alone does not read such a bean. - A pre-flight matched by several handlers with
@CrossOriginrules is answered from the first handler's rules. Spring allows it from any origin with credentials. - An
Originlonger than 1024 characters, or with characters other than visible US-ASCII, is refused. Spring echoes the latter. - Origin patterns are matched in linear time. Spring's regular expressions can take the square or cube of the origin's length with several
*.