Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

An application serves a browser UI with form login under /** and a machine API with JWT under /api/**. How do you configure two SecurityFilterChain beans, and what goes wrong if you get the ordering or matchers wrong?

We declare two SecurityFilterChain beans: the API chain with @Order(1) and http.securityMatcher("/api/**"), configured for JWT, stateless sessions and 401 responses, and the UI chain with a lower priority and no securityMatcher, configured for form login, sessions and CSRF. FilterChainProxy uses the first chain whose securityMatcher matches, and a chain without one matches every request, so if the catch-all UI chain is ordered first, the API chain is never used and API clients get login redirects.

Why this question is asked

Many applications serve two very different kinds of clients: people in a browser, who log in with a form and keep a session cookie, and machines, which send a bearer token on every call and expect JSON errors. Trying to serve both from one chain leads to compromises such as CSRF disabled for everyone or APIs that redirect to a login page. Interviewers ask this design question because it tests whether we understand how FilterChainProxy picks a chain and what each chain controls. In this answer, we will recap chain selection, write the two beans, see what goes wrong when the order or matchers are wrong, compare the settings of the two chains, and test both entry points.

1A Quick Recap: How FilterChainProxy Picks a Chain

Spring Security can hold several SecurityFilterChain beans. Each has a request matcher, set with http.securityMatcher(...), that decides which requests the chain is responsible for. FilterChainProxy sorts the chains by their @Order, lowest value first, and for each request uses the first chain whose matcher matches. Only that chain's filters run; the other chains are not consulted at all.

Two details shape the whole design. A chain built without securityMatcher matches every request, so it acts as a catch-all. And a chain is chosen as a whole: its authentication method, session policy, CSRF setting and error handling all come together. There is no merging of rules across chains.

2Writing the Two Beans

The API chain gets the highest priority and a matcher that limits it to /api/**. The UI chain comes second and has no matcher, so it handles everything else.

Java
@Configuration
@EnableWebSecurity
class SecurityConfig {
@Bean @Order(1)
SecurityFilterChain api(HttpSecurity http) throws Exception {
http.securityMatcher("/api/**") // only API requests
.authorizeHttpRequests(a -> a.anyRequest().authenticated())
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())) // 401 on missing token
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.csrf(c -> c.disable()); // bearer header, no cookies
return http.build();
}
@Bean @Order(2)
SecurityFilterChain ui(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(a -> a // no securityMatcher: everything else
.requestMatchers("/login", "/css/**", "/error").permitAll()
.anyRequest().authenticated())
.formLogin(Customizer.withDefaults()) // 302 to /login when needed
.logout(Customizer.withDefaults()); // sessions and CSRF stay on
return http.build();
}
}
// GET /api/orders, no token -> api chain -> 401, WWW-Authenticate: Bearer
// GET /orders, no session -> ui chain -> 302 Location: /login
Step throughWhich chain handles a request
  1. Does the request match /api/** (order 1)?
    YesAPI chain: JWT, stateless, 401NoTry the next chain
  2. UI chain (order 2) matches everythingform login, session, CSRF, 302 to /login

2 steps in order. Play them, or step through them one at a time.

The first matching chain wins, so the specific chain must come first.

Notice that the authorization rules in the API chain do not need to mention /api, because the chain only ever sees API requests. Notice also that securityMatcher and requestMatchers are different things: securityMatcher decides whether this chain handles the request at all, requestMatchers inside authorizeHttpRequests decide the rules once it does.

3What Goes Wrong With the Wrong Order

Suppose someone gives the UI chain @Order(1) and the API chain @Order(2), or forgets @Order entirely so the order is undefined. The UI chain has no securityMatcher, so it matches /api/orders too. FilterChainProxy picks it, and the API chain is never used for any request.

The symptoms are confusing. A machine client calling GET /api/orders without a session receives a 302 redirect to /login, or, if it follows redirects, an HTML login page with status 200. A POST with a valid bearer token fails with 403, because the UI chain does not understand bearer tokens and enforces CSRF on the POST. Nothing in the logs says 'wrong chain', which is why this is a classic.

Java
// UI chain ordered first (wrong)
// GET /api/orders Authorization: Bearer eyJ... -> 302 Location: /login
// POST /api/orders Authorization: Bearer eyJ... -> 403 (CSRF token missing)

Spring Security protects against part of this mistake: if a catch-all chain is ordered before another chain, it fails at startup with an error saying a universal match pattern is defined before other patterns (check your version's exact message). It cannot protect against a matcher that is simply too broad or wrong, such as securityMatcher("/api") without the /**, which matches only the exact path /api and sends /api/orders to the UI chain.

4Each Chain Has Its Own Settings

Because a chain is chosen as a whole, every security behaviour must be set per chain. That is the point of having two: each client type gets the behaviour that suits it.

Settings of the two chains
SettingAPI chain (/api/**)UI chain (everything else)
AuthenticationJWT bearer tokenform login
SessionSTATELESS, never createdcreated on login, cookie
CSRFdisabled, no cookiesenabled, token in forms
Not authenticated401 + WWW-Authenticate302 redirect to /login
Access denied403, JSON body403 error page
Order@Order(1), securityMatcher@Order(2), no matcher

The exception handling difference matters most to clients. The API chain's entry point returns 401 with a WWW-Authenticate header, which API clients and libraries understand. The UI chain's entry point redirects to the login page, which is right for a person and wrong for a script.

5Testing Both Entry Points

The configuration is only proven when both client types are tested against it. With MockMvc and spring-security-test we can send a JWT to the API and a form login to the UI in the same test class, and assert the different responses.

Java
@SpringBootTest
@AutoConfigureMockMvc
class TwoChainsTest {
@Autowired MockMvc mvc;
@Test void apiWithoutTokenGets401NotRedirect() throws Exception {
mvc.perform(get("/api/orders"))
.andExpect(status().isUnauthorized()) // 401
.andExpect(header().exists("WWW-Authenticate"));
}
@Test void apiPostWithJwtNeedsNoCsrf() throws Exception {
mvc.perform(post("/api/orders").with(jwt()).contentType(APPLICATION_JSON).content("{}"))
.andExpect(status().isCreated()); // 201
}
@Test void uiWithoutSessionRedirectsToLogin() throws Exception {
mvc.perform(get("/orders"))
.andExpect(status().is3xxRedirection()) // 302
.andExpect(redirectedUrlPattern("**/login"));
}
@Test void uiPostWithoutCsrfIsRejected() throws Exception {
mvc.perform(post("/orders").with(user("alice")))
.andExpect(status().isForbidden()); // 403
}
}

These four tests catch every mistake from the previous sections: a wrong order makes the first two fail, and a missing CSRF setting on the UI makes the last one fail. They take seconds and should run on every build.

6Follow-up questions

Can the UI chain also have a securityMatcher?

Yes, and some teams prefer explicit matchers on every chain. But then requests matching no chain get no security filters at all, so we must be sure every path is covered. Keeping one catch-all chain last is the safer default, because nothing can fall through unprotected.

What if the browser UI calls the /api endpoints with its session?

Then those calls go to the API chain, which does not accept sessions, and they fail with 401. Either the UI obtains a token and sends it as a bearer header, or the UI uses separate endpoints under the UI chain, or a backend-for-frontend holds the token. Mixing session and token authentication in one chain brings back the need for CSRF.

Does Spring Boot's default chain interfere?

No. Spring Boot's auto-configured default chain backs off as soon as the application defines its own SecurityFilterChain bean, so only our two chains exist. Printing the chains at startup with debug logging confirms it.

7Conclusion

In this answer, we configured two SecurityFilterChain beans: an API chain with @Order(1) and securityMatcher("/api/**"), using JWT, stateless sessions and 401 responses, and a catch-all UI chain ordered after it, using form login, sessions and CSRF. FilterChainProxy uses the first matching chain, and a chain without securityMatcher matches everything, so a wrong order sends API calls to the login page and breaks their POSTs. Each chain owns its own CSRF, session and exception handling, and tests for both entry points prove the setup.

What to say in the interviewAbout 80 seconds aloud

Open with

I would declare two SecurityFilterChain beans. The first has @Order(1) and http.securityMatcher("/api/**"), so it only handles API requests; it uses oauth2ResourceServer with JWT, a STATELESS session policy, CSRF disabled because the bearer token is a header, not a cookie, and its entry point returns 401 with WWW-Authenticate.

Then, if they want more

The second has @Order(2) and no securityMatcher, so it matches every other request; it uses form login, sessions and CSRF, and redirects unauthenticated users to the login page. FilterChainProxy picks the first chain whose securityMatcher matches, and only that chain's filters run.

That is why the order matters: a chain without securityMatcher matches everything, so if the UI chain came first, API calls would be handled by it, a GET would get a 302 to the login page and a POST with a valid token would fail CSRF with 403.

Spring Security catches the obvious case of a catch-all ordered first at startup, but not a matcher that is wrong, like /api without the double star. Each chain has its own session, CSRF and exception handling, which is the whole point.

I would test both entry points with MockMvc and spring-security-test: API without a token gets 401, API POST with jwt() works, UI without a session redirects, UI POST without CSRF is forbidden.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Security reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "An application serves a browser UI with form login under /** and a machine API with JWT...": https://scrivio-interview-library.netlify.app/spring-boot/security-architecture/8767e84121/