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

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:

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

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.

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:

  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

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.

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:

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

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:

Where the rules apply

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:

See also