Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A custom authentication filter declared as a Spring @Component and also added to the SecurityFilterChain with addFilterBefore runs twice per request. Why, and how do you fix it?

Spring Boot automatically registers every Filter bean it finds in the application context with the servlet container, so a filter declared as a @Component already runs once in the main servlet filter chain. Adding the same bean to the SecurityFilterChain with addFilterBefore makes it run a second time inside Spring Security's FilterChainProxy. The fix is to not make it a bean and create it with new in the security configuration, or to keep the bean and register a FilterRegistrationBean for it with setEnabled(false); extending OncePerRequestFilter also stops repeats within one request dispatch, and we confirm the result from the filter registrations shown in startup logs or the Actuator mappings view.

Why this question is asked

This bug is common because both steps look correct on their own. Making the filter a @Component lets it receive injected dependencies, and adding it to the security chain puts it in the right place relative to Spring Security's own filters. The result is a token being validated twice per request, which wastes time, doubles calls to an identity provider, and in some filters causes visible errors. Interviewers ask it to check whether we understand that there are two filter chains in a Spring Boot application and how filters get into each. In this answer, we will recap the two chains, reproduce the double execution, explain why it happens, look at the fixes and their trade-offs, and show how to verify the registrations.

1A Quick Recap of the Two Filter Chains

A Spring Boot web application has two levels of filters. The outer level is the servlet container's filter chain, the one Tomcat or Jetty runs for every request. Spring Boot fills it automatically: when it starts the embedded container, it looks for beans of type Filter, and for FilterRegistrationBean objects, and registers each one with the container, by default for all URLs.

Spring Security is one of those filters. It registers a single filter, a DelegatingFilterProxy that delegates to the FilterChainProxy, usually under the name springSecurityFilterChain. Inside FilterChainProxy is the inner level: one or more SecurityFilterChain objects, each with its own ordered list of security filters, configured through HttpSecurity. A filter we add with addFilterBefore lives in that inner list. The inner filters are not container filters; FilterChainProxy calls them itself.

Step throughWhere a filter can run in Spring Boot
  1. Servlet container chainEvery Filter bean registered automatically by Boot
  2. Our TokenFilter (as a bean)Run 1: registered because it is a @Component
  3. springSecurityFilterChainOne container filter: FilterChainProxy
  4. Security filters from HttpSecurityIncludes our TokenFilter again: run 2
  5. DispatcherServlet and controllerReached after both runs

5 layers, from the top down. Step through them one at a time.

2Reproducing the Double Execution

Here is the filter and the configuration that cause the problem. The filter logs each time it validates a token.

Java
@Component // (1) a bean, so Boot registers it with the container
public class TokenFilter implements Filter {
private final TokenVerifier verifier;
public TokenFilter(TokenVerifier verifier) { this.verifier = verifier; }
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
log.info("validating token");
verifier.verify((HttpServletRequest) req); // remote call to the identity provider
chain.doFilter(req, res);
}
}
@Bean
SecurityFilterChain api(HttpSecurity http, TokenFilter tokenFilter) throws Exception {
http.addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class) // (2) added again
.authorizeHttpRequests(a -> a.anyRequest().authenticated());
return http.build();
}
// GET /orders
// INFO TokenFilter - validating token <- container chain
// INFO TokenFilter - validating token <- inside FilterChainProxy
Step throughOne request, the same filter twice
TomcatTokenFilterFilterChainProxyController
doFilter (container chain)
validate token: run 1
chain.doFilter
doFilter (security chain)
validate token: run 2
chain.doFilter
handle request
response

8 messages in order. Play them, or step through them one at a time.

Notice where each log line comes from. The first run is from the container chain, because the bean was found and registered automatically. The second run is inside the security chain, because we added the same object there. It is one instance, called twice by two different chains.

3Why OncePerRequestFilter Is Only Part of the Answer

A natural first reaction is to extend OncePerRequestFilter. It records in a request attribute, named after the filter, that it has already run, and skips doFilterInternal on later calls for the same request. Because both chains handle the same request object, the second call is skipped, so the double validation disappears.

Java
@Component
public class TokenFilter extends OncePerRequestFilter {
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
log.info("validating token");
verifier.verify(req);
chain.doFilter(req, res);
}
}
// GET /orders
// INFO TokenFilter - validating token <- only once now; second call sees the attribute

But there is a catch. The run that survives is the first one, in the container chain, which happens before Spring Security has started, outside the place we chose with addFilterBefore. Anything it puts in the SecurityContext can be lost or overwritten when Spring Security sets up its own context, and the filter runs for URLs our security chain does not even cover. So OncePerRequestFilter is the right base class for filters in general, since it also protects against repeats on forward and error dispatches, but it hides the real problem here rather than fixing it.

4Fix 1: Do Not Make the Filter a Bean

The simplest fix is to remove @Component and create the filter in the security configuration. Its dependencies are still beans, so we inject them into the configuration method and pass them to the constructor. Spring Boot no longer sees a Filter bean, so it registers nothing with the container, and the filter runs only where we placed it.

Java
public class TokenFilter extends OncePerRequestFilter { /* no @Component */ }
@Bean
SecurityFilterChain api(HttpSecurity http, TokenVerifier verifier) throws Exception {
http.addFilterBefore(new TokenFilter(verifier), UsernamePasswordAuthenticationFilter.class)
.authorizeHttpRequests(a -> a.anyRequest().authenticated());
return http.build();
}
// GET /orders
// INFO TokenFilter - validating token <- once, inside the security chain

The cost is that the filter is not a managed bean, so it does not get lifecycle callbacks or proxies such as @Transactional, which a security filter should not need anyway.

5Fix 2: Keep the Bean but Disable Its Container Registration

If the filter must stay a bean, for example because other components look it up or it uses bean lifecycle methods, we tell Spring Boot not to register it with the container. A FilterRegistrationBean for that filter with setEnabled(false) replaces the automatic registration and switches it off.

Java
@Bean
FilterRegistrationBean<TokenFilter> tokenFilterRegistration(TokenFilter filter) {
FilterRegistrationBean<TokenFilter> reg = new FilterRegistrationBean<>(filter);
reg.setEnabled(false); // bean exists, but Tomcat never runs it directly
return reg;
}

The filter now runs only inside FilterChainProxy. This works for any Filter bean, including filters from libraries that are beans we cannot change.

6Verifying the Registrations

After the fix, we confirm it rather than trusting the log once. At startup, with logging for org.springframework.boot.web.servlet set to DEBUG (check the exact logger names for your Boot version), Spring Boot logs each filter it maps to the container, so tokenFilter should no longer appear among them. The Actuator mappings endpoint, /actuator/mappings, lists the servlet filters registered with the container, and Spring Security logs the filters of each SecurityFilterChain at startup, at DEBUG level, so we can check that TokenFilter appears exactly once in the right place. A test with MockMvc that counts calls to a mocked TokenVerifier, expecting exactly one per request, keeps the bug from coming back.

7Follow-up questions

Does the same problem happen with filters added to multiple SecurityFilterChain beans?

Only one SecurityFilterChain matches each request, the first whose request matcher fits, so a filter added to two chains runs once per request. The double run comes specifically from being in both the container chain and a security chain.

Why does Spring Boot register Filter beans automatically?

It makes simple filters easy: declare a bean and it runs for every request, with order taken from @Order or Ordered. That convenience is exactly what surprises people when they also add the filter somewhere else by hand.

Would @Order on the bean change anything?

It changes where the filter runs in the container chain, but it still runs there and again in the security chain. Order cannot remove a registration; only not being a bean or a disabled FilterRegistrationBean can.

8Conclusion

In this answer, we saw that a filter marked @Component is registered by Spring Boot with the servlet container, and adding the same bean with addFilterBefore puts it inside Spring Security's FilterChainProxy too, so it runs twice. Removing @Component and creating it in the security configuration, or disabling its container registration with a FilterRegistrationBean and setEnabled(false), makes it run once in the right place. OncePerRequestFilter prevents repeats within one request but hides this cause, and startup logs, Actuator mappings and a counting test confirm the fix.

What to say in the interviewAbout 100 seconds aloud

Open with

There are two filter chains in a Spring Boot app. The servlet container has its own chain, and Spring Boot automatically registers every Filter bean into it. Spring Security is just one filter in that chain, the FilterChainProxy, and inside it there is a second chain of security filters configured through HttpSecurity.

Then, if they want more

Because the authentication filter is a Component, Boot registers it in the container chain, so it runs once there. Then addFilterBefore puts the same instance into the security chain, so FilterChainProxy calls it again. That is why we see the token validated twice.

Extending OncePerRequestFilter would make the second call skip, because it marks the request with an attribute, but the run that survives is the one in the container chain, outside Spring Security and outside the position we chose, so it hides the problem. The real fix is to have only one registration.

The simplest way is to remove Component and create the filter with new in the security configuration, injecting its dependencies into the bean method. If it has to remain a bean, I add a FilterRegistrationBean for it with setEnabled false, which tells Boot not to put it in the container chain.

I would still extend OncePerRequestFilter, because it protects against forwards and error dispatches. Then I verify: the startup logs or the Actuator mappings endpoint show which filters the container has, Spring Security's debug log lists the security chain, and a MockMvc test asserts the verifier is called exactly once per request.

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 official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
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 "A custom authentication filter declared as a Spring @Component and also added to the...": https://scrivio-interview-library.netlify.app/java/behavioral-patterns/aae91b5709/