
# 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:

1. for most requests, first sends an `OPTIONS` **pre-flight** with `Origin`, `Access-Control-Request-Method` and often `Access-Control-Request-Headers`, and asks whether the call is allowed;
2. sends the actual request with an `Origin` header;
3. lets the page read the answer only when it carries an `Access-Control-Allow-Origin` that 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

```dart
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:

```dart
@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:

```text
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`, `allowPrivateNetwork` and `maxAge` win.
- **Without `methods`**, the method the handler is mapped to is allowed, as in Spring: `DELETE` for a `@DeleteMapping`, `GET` for a `@GetMapping`. **Not `HEAD`**: a cross-origin `HEAD` to a `GET` handler is refused. Write `methods: ['GET', 'HEAD']` when pages send it.
- **`allowCredentials: true` or `allowPrivateNetwork: true` without `origins` or `originPatterns`** (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 for `origins: ['*']`. See [Startup checks](controllers/startup-checks.md).

### `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 a `500` (a `StateError`), 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 `@CrossOrigin` nor the `addCorsMappings` rules widen it: an origin, a header or a max age they would add is not added.
- **Where it returns `null`**, `@CrossOrigin` and the mappings apply.
- **The name counts, not the type.** A `@Bean` method named `corsConfigurationSource()` 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 a `CorsConfigurationSource` is 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 `allowedMethods` allow `GET` and `HEAD`. Call `applyPermitDefaultValues()` for the permissive defaults.
- **`*` with credentials or a private network** fails each cross-origin request that reaches the check (a `500`).

`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:

```dart
// 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` / `allowedOrigins`** are whole origins, compared without case: `https://shop.example` matches `https://SHOP.example`. `*` allows any origin, and the answer is then `Access-Control-Allow-Origin: *`.
- **`originPatterns` / `allowedOriginPatterns`** are compared with case. `*` matches any text, as Spring's `.*`:
  - `https://*.shop.example` takes `https://eu.shop.example` and `https://a.b.shop.example`, not `https://shop.example`;
  - `*.shop.example` takes any scheme; `*localhost*` takes any `localhost` origin;
  - a port list at the end takes the ports listed: `http://localhost:[3000,3001]`;
  - `[*]` takes any port or none: `http://localhost:[*]` takes `http://localhost` and `http://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 the `Origin` header.
- **An `Origin` longer 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 `Origin` with a character other than visible US-ASCII** (a space, a control character, a letter beyond ASCII) is refused with a `403`, 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.com` also takes `https://evil.com/.example.com`. No browser sends such an `Origin`, and other clients can send any `Origin` anyway.

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:

```dart
@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`:

1. adds `Vary: Origin`, `Vary: Access-Control-Request-Method` and `Vary: Access-Control-Request-Headers`, a CORS request or not;
2. refuses an `Origin` that is not visible US-ASCII;
3. stops there, allowing the request, when it is not a CORS request;
4. 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);
5. checks the origin;
6. checks the method: for a pre-flight the one in `Access-Control-Request-Method`, otherwise the request's own;
7. for a pre-flight, checks every header of `Access-Control-Request-Headers`;
8. 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 `OPTIONS` request that is not a pre-flight, to a path without an `OPTIONS` handler, gets `200` with `Allow`. The global rules apply to it first, with `OPTIONS` as 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 a `ResponseEntity` or an `ErrorResponse`) adds its names to these, rather than replacing them, as Spring's `HttpEntityMethodProcessor` merges 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 `401` and `403` answers 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 `@CrossOrigin` or `applyPermitDefaultValues()` gives way to the other side's list: it never widens what the other side sets. `@CrossOrigin()` without `origins` keeps 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`, `allowPrivateNetwork` and `maxAge`** of the more specific side win when they are set. `@CrossOrigin` always brings a `maxAge` (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 says `Access-Control-Allow-Credentials: true` with the exact origin. Browsers refuse `*` with credentials. So `allowCredentials: true` needs listed origins or patterns:
  - `@CrossOrigin`: the startup fails;
  - an `addCorsMappings` mapping: every request to its paths is a `500`;
  - the `corsConfigurationSource` bean: every cross-origin request it allows by `*` is a `500`.
- **Private Network Access** (Chrome): a page of a public site that calls a server on `localhost` or an office network sends a pre-flight with `Access-Control-Request-Private-Network: true`. With `allowPrivateNetwork: true`, the answer adds `Access-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=None` and `Secure`. See [Sessions](sessions.md).

## 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-strategy` so the request knows its real scheme, host and port from the proxy's headers (see [Behind a reverse proxy](server/reverse-proxy.md));
- 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](server/ssl.md)).

## 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](static-resources.md).
- **A `404`** (no handler): the global rules.
- **Another handler mapping** (WebSocket endpoints): only the bean's rules where it has some. The `addCorsMappings` rules and `@CrossOrigin` belong to the controllers; a WebSocket endpoint checks the `Origin` of a handshake itself. See [WebSocket](server/websocket.md).

`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)

```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. `maxAge` takes a `Duration`.
- The `corsConfigurationSource` bean 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 `@CrossOrigin` rules is answered from the first handler's rules. Spring allows it from any origin with credentials.
- An `Origin` longer 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 `*`.

## See also

- [WebMvcConfigurer](web-mvc-configurer.md)
- [Filters](filters.md)
- [Static resources](static-resources.md)
- [Behind a reverse proxy](server/reverse-proxy.md)
- [Startup checks](controllers/startup-checks.md)
- [WebSocket](server/websocket.md)
