
# Headers and CORS

The chain writes security headers on every response: `X-Content-Type-Options: nosniff`, no caching, `X-Frame-Options: DENY`, `X-XSS-Protection: 0` and, over HTTPS, HSTS. It also handles CORS before any security check, with the same rules the router uses, so pre-flight requests are answered and cross-origin calls work with security on.

## Why

A few headers close whole classes of browser attacks: clickjacking (a page framed by another site), content sniffing, a login page left in a shared computer's cache, a downgrade to plain HTTP. They cost nothing and are easy to forget, so they are on by default. CORS must run before security: a pre-flight carries no credentials, and would otherwise be refused with `401`.

## Example

```dart
@Bean()
SecurityFilterChain filterChain(HttpSecurity http) => http
    .authorizeHttpRequests((auth) => auth.anyRequest().authenticated())
    .formLogin()
    .headers((h) => h
        .contentSecurityPolicy("default-src 'self'; frame-ancestors 'self'")
        .referrerPolicy('strict-origin-when-cross-origin')
        .frameOptions(XFrameOptionsMode.sameOrigin)
        .httpStrictTransportSecurity(const HstsHeaderWriter(maxAge: Duration(days: 730), preload: true)))
    .build();
```

## The headers

| Header | Default | Option |
|---|---|---|
| `X-Content-Type-Options: nosniff` | sent | `contentTypeOptions(enabled:)` |
| `Cache-Control: no-cache, no-store, max-age=0, must-revalidate`, `Pragma: no-cache`, `Expires: 0` | sent | `cacheControl(enabled:)` |
| `X-Frame-Options: DENY` | sent | `frameOptions(XFrameOptionsMode.sameOrigin)`, `null` to not send it |
| `X-XSS-Protection: 0` | sent | `xssProtection(enabled:)` |
| `Strict-Transport-Security: max-age=31536000; includeSubDomains` | sent over HTTPS only | `httpStrictTransportSecurity(HstsHeaderWriter(maxAge:, includeSubDomains:, preload:))`, `null` to not send it |
| `Content-Security-Policy` | not sent | `contentSecurityPolicy(policy)` |
| `Referrer-Policy` | not sent | `referrerPolicy(policy)` |
| your own | | `addHeaderWriter(writer)` |

- A controller that sets its own `Cache-Control` replaces the cache headers, and the `Pragma` and `Expires` written here are removed too. Turn `cacheControl` off for a chain serving only public, cacheable content.
- `headers((h) => h.disable())` sends no security headers at all.
- `headers((h) => h.defaultsDisabled())` drops the defaults. After it, `frameOptions`, `httpStrictTransportSecurity`, `contentTypeOptions`, `xssProtection` and `cacheControl` have no effect (unlike Spring, which adds the headers configured after it); only `contentSecurityPolicy`, `referrerPolicy` and `addHeaderWriter` still add headers.
- `preload` asks to be built into browsers' HSTS lists; it is hard to undo, so it is off by default.

## CORS

CORS is on in every chain, with the router's rules, pre-flight requests included:

1. The rules of the `CorsConfigurationSource` bean named `corsConfigurationSource`, alone, where it has some (as Spring Security applies that bean). A bean of the type with another name, such as `apiCors`, is ignored; several never fail the start; a bean of that name of another type does, as in Spring.
2. Else the `WebMvcConfigurer` mappings (`addCorsMappings`) and the `@CrossOrigin` of the handler the router would call, chosen with its `consumes`, `produces` and `headers` too.

The handler mappings are asked in order, as for the request itself: a request another mapping takes, such as a WebSocket handshake, gets only the bean's rules, never the `addCorsMappings` ones. The router leaves a request the filter allowed as it is, so CORS works the same with and without this starter.

A request's origin and method are checked: a `HEAD` or `DELETE` the rules do not list is a `403`, before the security checks.

```dart
// Other rules for this chain only.
.cors((c) => c.configurationSource(
    UrlBasedCorsConfigurationSource()
      ..registerCorsConfiguration(
        '/api/**',
        CorsConfiguration(allowedOrigins: ['https://shop.example'], allowCredentials: true)
          ..applyPermitDefaultValues(),
      )))
```

`cors((c) => c.disable())` turns it off for a chain. The rules themselves are described on [CORS in the web starter](../spring-boot-starter-web/cors.md).

## Behind a proxy

HSTS is sent only when the request is HTTPS. Behind a proxy that terminates TLS, the server sees `http` until the web starter reads forwarded headers (`server.forward-headers-strategy`); see [Behind a reverse proxy](../spring-boot-starter-web/server/reverse-proxy.md).

## In Spring (Java)

```java
http.headers(h -> h
    .contentSecurityPolicy(csp -> csp.policyDirectives("default-src 'self'"))
    .frameOptions(f -> f.sameOrigin()))
    .cors(Customizer.withDefaults());
```

Differences: CORS is on by default (Spring needs `.cors()`); where the `corsConfigurationSource` bean has no rule for a path, the pre-flight is answered from the handler's `@CrossOrigin` (Spring's `CorsFilter` answers it with a `200` without CORS headers); `defaultsDisabled()` ignores later default-header calls. `Clear-Site-Data` on logout and `redirectToHttps()` are not here yet.

## See also

- [CORS](../spring-boot-starter-web/cors.md)
- [The filter chain](filter-chain.md)
- [Differences from Spring](differences.md)
