Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 39 ยท Filter Chain and Configuration

Multiple SecurityFilterChains in One Application

Use several SecurityFilterChain beans with securityMatcher and @Order to give an API token security and a web UI session login in the same Spring Boot application.

One application often serves two kinds of clients. A browser uses pages and cookies: it wants a login form, sessions and CSRF protection. A mobile app or another service calls /api/** with a token: it wants JSON 401 errors, no sessions and no redirect to a login page. One chain with a pile of conditions cannot serve both cleanly. Spring Security's answer is to define several SecurityFilterChain beans, each with its own matcher and its own filters.

This lesson shows how FilterChainProxy chooses the chain, how to write the matcher with securityMatcher, how @Order settles overlaps, and how to avoid the classic trap of a chain that swallows every request.

How a chain is selected

Recall from the filter chain that FilterChainProxy holds a list of chains and uses the first one whose request matcher matches. A chain without an explicit matcher matches every request. So with two chains:

  • the order of the beans decides which one is asked first, and
  • a "catch-all" chain must come last, or it hides the others.

You set the order with @Order on the bean method (lower numbers first). If you forget it, Spring may see the beans in an arbitrary order and, since Spring Security 6, complains at startup when a chain without a matcher is followed by another chain ("a filter chain that matches any request has already been configured").

Two chains, side by side

Java
@Configuration
@EnableWebSecurity
class SecurityConfig {

    @Bean
    @Order(1)
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http
            .securityMatcher("/api/**")
            .authorizeHttpRequests(a -> a
                .requestMatchers("/api/public/**").permitAll()
                .anyRequest().authenticated())
            .csrf(csrf -> csrf.disable())
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .httpBasic(basic -> basic.authenticationEntryPoint(
                    new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)));
        return http.build();
    }

    @Bean
    @Order(2)
    SecurityFilterChain web(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(a -> a
                .requestMatchers("/", "/login", "/css/**").permitAll()
                .anyRequest().authenticated())
            .formLogin(f -> f.loginPage("/login"))
            .logout(Customizer.withDefaults());
        return http.build();
    }
}

securityMatcher("/api/**") limits the chain to API URLs. The web chain has no matcher, so it receives everything else. Note the two different authorizeHttpRequests blocks: the /api/** prefix is repeated inside the first chain because the matcher only selects the chain; rules inside it are still evaluated normally.

Do not confuse the two methods:

  • securityMatcher(...) decides whether this chain handles the request at all.
  • requestMatchers(...) inside authorizeHttpRequests decides which rule applies to a request the chain already handles.

What each chain gives you

Concern API chain Web chain
Credentials Authorization header (Basic or Bearer token) Login form, session cookie
Session Stateless Created after login
CSRF Disabled (header auth) Enabled
Unauthenticated response 401 with no redirect Redirect to /login
Error format JSON HTML page

Splitting also gives you freedom for different entry points, different password sources (the API may accept API keys; the web UI users from a database) and different headers or CORS settings.

A runnable chain selector

The following stand-in shows the selection algorithm and why order matters. Each chain has a matcher and a name; the selector returns the first match. It also checks for the dangerous configuration where a catch-all comes first.

Java FilterChainProxy: the first matching chain wins

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Matching by more than a path

securityMatcher accepts any RequestMatcher. Besides path patterns you can match on a header or a host:

Java
http.securityMatcher(request -> "internal".equals(request.getHeader("X-Zone")));
http.securityMatcher(PathPatternRequestMatcher.withDefaults().matcher(HttpMethod.POST, "/hooks/**"));

Webhooks are a good use: a payment provider calls /hooks/payments with a signature header, not a user session. A small chain with a custom signature filter and no CSRF serves it, while the rest of the application stays untouched.

Here is a webhook chain in miniature: the matcher selects only /hooks/**, and a filter verifies an HMAC signature of the body, a common way to authenticate a service that has no user session. It uses the JDK's Mac.

Java A webhook chain: signature instead of a session

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Different users per chain

By default all chains share the application's UserDetailsService/AuthenticationManager. For separate sources, set a manager per chain:

Java
http.authenticationManager(apiAuthenticationManager)   // for this chain only

or add an AuthenticationProvider with http.authenticationProvider(apiKeyProvider). Keep the sources separate when the populations are separate: admin staff from LDAP, customers from a database.

Ignoring a path with its own chain

Sometimes a path should bypass authentication completely, for example /actuator/health. Rather than web.ignoring(), give it a tiny first chain, which keeps headers and logging:

Java
@Bean @Order(0)
SecurityFilterChain health(HttpSecurity http) throws Exception {
    http.securityMatcher("/actuator/health/**")
        .authorizeHttpRequests(a -> a.anyRequest().permitAll())
        .csrf(csrf -> csrf.disable());
    return http.build();
}

Boot's actuator already ships a chain for endpoints, so check what exists with logging.level.org.springframework.security=DEBUG before adding one (the log lists every chain at startup).

Pitfalls

  • Catch-all not last. The most common bug. Give it the highest order number.
  • Forgetting securityMatcher and using only rules. Without it, the chain matches everything and later chains are unreachable.
  • Duplicating cross-cutting settings. Headers, CORS and logging apply per chain. Extract shared customizers into a method such as Customizer<HttpSecurity> and apply it with http.with(...) or a plain helper.
  • Different session policies with a shared cookie. If the API chain is stateless but the web chain creates sessions, a browser calling the API with a cookie gets no benefit from it: the API chain ignores the session.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does securityMatcher("/api/**") do?

    It is the chain's own request matcher. Rules inside authorizeHttpRequests then apply to the requests the chain handles.
  2. 2. You have an API chain with securityMatcher and a catch-all web chain. Which should have the lower @Order number?

    Lower numbers are asked first. The specific chain must come first or the catch-all swallows its requests.
  3. 3. Which is a good reason for a separate chain for /api/**?

    APIs and browser UIs need different entry points, session policy and CSRF handling.
  4. 4. How many chains run for a single request?

    FilterChainProxy runs only the first matching SecurityFilterChain.

Summary

  • Define several SecurityFilterChain beans when different clients need different mechanisms.
  • securityMatcher selects the chain; requestMatchers selects rules inside it.
  • Only the first matching chain runs, so order specific chains before the catch-all with @Order.
  • Split by client type: stateless token API versus session-based web UI; webhooks can have their own chain.
  • Share common settings through helper methods rather than copy and paste.

Next: Writing custom filters