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

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

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).
formLogin([customizer]) Login with a form (see Form login and HTTP Basic).
httpBasic([customizer]) HTTP Basic.
oauth2ResourceServer((s) => s.jwt()) Bearer and DPoP tokens (see JWT resource servers).
oauth2Login([customizer]) Single sign-on (see Single sign-on).
csrf((c) => ...) CSRF protection (see CSRF).
cors([customizer]) CORS (see Headers and CORS).
headers((h) => ...) Security headers.
sessionManagement((s) => ...) Sessions (see Sessions).
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

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:

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.

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). Spring Security and Spring Boot have neither the log nor the indicator.

In Spring (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