
# The filter chain

Every request passes a chain of security filters before it reaches the router: one loads the user, one writes headers, one checks the CSRF token, one logs users in, one checks the access rules. You describe the chain with `HttpSecurity` in a `SecurityFilterChain` bean; without one, the starter makes a default chain that needs a login for everything.

## Why

Security checks belong in front of the controllers, in one place, so that a new endpoint is protected by default and no controller can forget a check. The chain is that place. `HttpSecurity` builds it from readable steps, and the starter puts the built-in filters in the right order.

## Example

```dart
@Configuration()
class SecurityConfig {
  // The API: tokens, no session, no CSRF (no cookies to forge).
  @Bean()
  @Order(1)
  SecurityFilterChain api(HttpSecurity http) => http
      .securityMatcher('/api/**')
      .authorizeHttpRequests((auth) => auth.anyRequest().authenticated())
      .oauth2ResourceServer((server) => server.jwt())
      .sessionManagement((s) => s.sessionCreationPolicy(SessionCreationPolicy.stateless))
      .build();

  // Everything else: pages with a login form. It matches every request, so it comes last.
  @Bean()
  @Order(2)
  SecurityFilterChain web(HttpSecurity http) => http
      .authorizeHttpRequests((auth) => auth
          .requestMatchers('/', '/public/**', '/sign-in').permitAll()
          .anyRequest().authenticated())
      .formLogin((form) => form.loginPage('/sign-in'))
      .addFilterAfter(AuditFilter(), UsernamePasswordAuthenticationFilter)
      .build();
}
```

## The default chain

Without a `SecurityFilterChain` bean, the starter declares one, as Spring Boot does:

- every request needs a login (`anyRequest().authenticated()`);
- form login with the generated page, and HTTP Basic;
- with `spring.security.oauth2.resourceserver.jwt.issuer-uri`, `jwk-set-uri` or `secret-key`, or a `JwtDecoder` bean: bearer tokens instead, and no default user;
- with OAuth2 client registrations: `oauth2Login()`, and bearer tokens too when there is a `JwtDecoder`;
- CSRF, headers, CORS, logout and the anonymous user.

Each bean method that takes an `HttpSecurity` gets a fresh builder.

## HttpSecurity

| Step | What it configures |
|---|---|
| `securityMatcher(pattern, ...)`, `securityMatcherOf(matcher)` | Which requests this chain handles; all when absent. |
| `authorizeHttpRequests((auth) => ...)` | The access rules (see [Request rules](authorize-http-requests.md)). |
| `formLogin([customizer])` | Login with a form (see [Form login and HTTP Basic](form-login.md)). |
| `httpBasic([customizer])` | HTTP Basic. |
| `oauth2ResourceServer((s) => s.jwt())` | Bearer and DPoP tokens (see [JWT resource servers](jwt.md)). |
| `oauth2Login([customizer])` | Single sign-on (see [Single sign-on](oauth2-login.md)). |
| `csrf((c) => ...)` | CSRF protection (see [CSRF](csrf.md)). |
| `cors([customizer])` | CORS (see [Headers and CORS](headers-and-cors.md)). |
| `headers((h) => ...)` | Security headers. |
| `sessionManagement((s) => ...)` | Sessions (see [Sessions](sessions.md)). |
| `logout((l) => ...)` | The logout endpoint. |
| `exceptionHandling((e) => ...)` | `authenticationEntryPoint` (what a client that must log in gets), `accessDeniedHandler` (what a denied one gets). |
| `anonymous((a) => ...)` | The anonymous user; `a.disable()` removes it. |
| `requestCache((r) => ...)` | Where the page to come back to after a login is kept. |
| `securityContext((s) => ...)` | The `SecurityContextRepository` that keeps the user between requests. |
| `authenticationManager(manager)`, `userDetailsService(service)` | Users for this chain only. |
| `addFilterBefore`, `addFilterAfter`, `addFilterAt` | Your own `WebFilter`, relative to a built-in filter class. |
| `build()` | The `SecurityFilterChain`. |

Every customizer takes a function that receives the configurer: `csrf((c) => c.disable())`.

## Several chains

- `securityMatcher('/api/**')` limits a chain to some paths. Order the beans with `@Order`: the first chain whose matcher fits handles the request.
- A chain that matches every request must come last, or the startup fails.
- A request that no chain matches goes on without any security filter, as in Spring: keep a last chain without `securityMatcher`.
- A chain without `authorizeHttpRequests` lets every request through, with a warning in the log.

## The built-in filters

In the order they run (`SecurityFilterOrder`):

| Order | Filter | Does |
|---|---|---|
| 100 | `SecurityContextHolderFilter` | Loads the user of the request into its own security context scope. |
| 200 | `HeaderWriterFilter` | Writes the security headers. |
| 300 | `CorsFilter` | Answers pre-flights and checks origins. |
| 400 | `CsrfFilter` | Checks the CSRF token. |
| 500 | `LogoutFilter` | Logs out at `POST /logout`. |
| 520, 560 | OAuth2 login filters | The redirect to the provider, the callback. |
| 600 | `UsernamePasswordAuthenticationFilter` | The form login. |
| 700, 800 | `DefaultLoginPageGeneratingFilter`, `DefaultLogoutPageGeneratingFilter` | The generated pages. |
| 890 | `DPoPAuthenticationFilter` | DPoP-bound tokens. |
| 900 | `BearerTokenAuthenticationFilter` | Bearer tokens. |
| 1000 | `BasicAuthenticationFilter` | HTTP Basic. |
| 1100 | `SecurityContextHolderAwareRequestFilter` | The request's user for the controllers. |
| 1200 | `AnonymousAuthenticationFilter` | The anonymous user when nobody logged in. |
| 1300 | `ExceptionTranslationFilter` | Turns security exceptions into `401`, a login redirect or `403`. |
| 1400 | `AuthorizationFilter` | Checks the access rules. |

## Filters of your own

A `WebFilter` (usually a `OncePerRequestFilter`) is placed relative to a built-in filter class:

```dart
final class AuditFilter extends OncePerRequestFilter {
  @override
  Future<void> doFilterInternal(
    ServerHttpRequest request,
    ServerHttpResponse response,
    WebFilterChain chain,
  ) {
    final user = SecurityContextHolder.getContext().authentication?.name;
    SpringLog('audit').info('${request.method} ${request.uri.path} by $user');
    return chain.doFilter(request, response);
  }
}

// In the chain:
.addFilterAfter(AuditFilter(), AuthorizationFilter)
```

`addFilterAt` puts it at the position of the built-in filter, right after it; the built-in filter stays. A class that is not a built-in filter is an `ArgumentError`.

## Where the chain runs

The whole security chain is one web filter of the web starter, at `spring.security.filter.order` (`-100` by default) among the other `WebFilter` beans. A filter with a lower order runs before security, one with a higher order after it.

## An authentication that outlives its request

Every request runs in a security context of its own, which ends with it. Code outside a request has none unless it opens one: a `@Scheduled` method, a timer, a listener of a stream opened at startup. An authentication it sets (`SecurityContextHolder.getContext().authentication = ...`) goes to the one context of the whole program and stays: everything else outside a request then acts as that user.

- **The log.** Each time it happens from a new place in the code, a WARN on `spring.security.context.ProgramWideAuthentication` names the place and the kind of authentication, never the user. Nothing is refused. An application that means it (one system user for all the background work) sets that logger to `error`.
- **The health.** With `management.health.securityContext.enabled=true`, `/actuator/health` has `securityContext`, always `UP`, with `programWideAuthentication` (whether there is one now) and `setOutsideRequests` (how many times since the start). It is off by default, so the health is Spring Boot's.
- **The fix** is a scope for the work:

```dart
await SecurityContextHolder.runWithContext(
  () => reports.sendFor(user),
  SecurityContextImpl(authentication),
);
```

Neither sees what is no authentication any more: a user's rows in a cache, a result in a field. For those, test with requests of several users at the same time: `withMockUsersAtOnce` (see [Testing](testing.md)). Spring Security and Spring Boot have neither the log nor the indicator.

## In Spring (Java)

```java
@Bean
@Order(1)
SecurityFilterChain api(HttpSecurity http) throws Exception {
  return http.securityMatcher("/api/**")
      .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
      .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
      .build();
}
```

The builder is Spring's. Customizers that take no settings are optional (`formLogin()` instead of `formLogin(Customizer.withDefaults())`).

## See also

- [Request rules](authorize-http-requests.md)
- [Filters](../spring-boot-starter-web/filters.md)
- [Differences from Spring](differences.md)
