Quick revision
The short answer
We extend OncePerRequestFilter: if the X-Service-Token header is absent we just continue the chain, if it is present we validate it, build an authenticated Authentication such as a PreAuthenticatedAuthenticationToken with the service's authorities, and set it in a new SecurityContext through the SecurityContextHolderStrategy; if it is invalid we clear the context and answer 401 through the entry point. We add it with http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class) or before BearerTokenAuthenticationFilter, so it always runs before authorization, and we make sure it is not also registered as a servlet filter. Better still, the filter only extracts the token and delegates validation to an AuthenticationProvider.
What to remember
In this answer, we wrote a OncePerRequestFilter that continues when the X-Service-Token header is absent, sets a new authenticated SecurityContext through the SecurityContextHolderStrategy when it is valid, and clears the context and answers 401 through the entry point when it is not. We added it with addFilterBefore() relative to UsernamePasswordAuthenticationFilter or BearerTokenAuthenticationFilter, so it runs before authorization, avoided registering it twice as a servlet filter, and saw that delegating validation to an AuthenticationProvider gives a cleaner and more auditable design.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We extend OncePerRequestFilter: if the X-Service-Token header is absent we just continue the chain, if it is present we validate it, build an authenticated Authentication such as a PreAuthenticatedAuthenticationToken with the service's authorities, and set it in a new SecurityContext through the SecurityContextHolderStrategy; if it is invalid we clear the context and answer 401 through the entry point. We add it with http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class) or before BearerTokenAuthenticationFilter, so it always runs before authorization, and we make sure it is not also registered as a servlet filter. Better still, the filter only extracts the token and delegates validation to an AuthenticationProvider.
Why this question is asked
A custom header for service-to-service calls is a common requirement, especially in older systems or during a migration to OAuth2. Writing the filter takes twenty lines, and getting it subtly wrong is just as easy: it runs twice, it lets invalid tokens through as anonymous, it leaves a user on a pooled thread, or it sits in the wrong place in the chain. Interviewers ask for the code and the placement because both matter. In this answer, we will recap what a filter in the security chain must do, write it, place it, avoid the double registration trap, and then improve it by delegating to an AuthenticationProvider.
1What a Security Filter Must Do
Every request to a protected path passes through a list of security filters. Authentication filters near the front establish who the caller is and put the result in the SecurityContext, the per-request holder of the current Authentication. AuthorizationFilter near the end checks the rules, such as hasAuthority("SERVICE"), against that Authentication.
So our filter has three cases. No header: this request is not ours, so we do nothing and continue; another filter may authenticate it, or it stays anonymous. Valid header: we create an authenticated Authentication and set it. Invalid header: the caller tried to authenticate and failed, so we stop and answer 401 rather than quietly continuing as anonymous.
- X-Service-Token header present?YesValidate itNoContinue the chain unchanged
- Token valid?YesSet an authenticated context, continueNoClear context, entry point answers 401
2 steps in order. Play them, or step through them one at a time.
Never turn a failed attempt into an anonymous request.
2Writing the Filter
OncePerRequestFilter is Spring's base class for filters that must run once per request even when the request is forwarded or dispatched again. We implement doFilterInternal().
Notice a few details. PreAuthenticatedAuthenticationToken with authorities is created already authenticated, which is what we want after our own check. We create a new context instead of changing the existing one, and we use the SecurityContextHolderStrategy rather than the static methods, which is the style Spring Security 6 recommends because it lets the strategy be configured as a bean. We pass null as credentials, so the token is never stored in the Authentication. And we do not save the context to a session: service calls are stateless, so the filter authenticates every request.
3Where It Goes in the Chain
The filter must run before AuthorizationFilter, otherwise the rules are checked before the caller is known. By convention we place it among the other authentication filters, with addFilterBefore() relative to a filter that is known to be in the chain.
Notice that addFilterBefore() with UsernamePasswordAuthenticationFilter works even when form login is not enabled. HttpSecurity uses the class only as a position in its known filter order, so the reference marks a slot among the authentication filters. Placing it there also means it runs before AnonymousAuthenticationFilter, which then sees an authenticated context and leaves it alone.
4The Double Registration Trap
If we annotate the filter with @Component, Spring Boot sees a Filter bean and registers it with the servlet container too. It then runs twice: once as an ordinary servlet filter, outside Spring Security, and once inside the chain. The servlet copy sets a context that the security chain's own context loading replaces, and an invalid token would be rejected before security logging or headers apply. It is wasted work at best and confusing behaviour at worst.
The simplest fix is not to make it a bean at all and create it in the configuration, as above. If it must be a bean, for example to inject dependencies, we tell Boot not to register it with the container.
5Better: Delegate Validation to an AuthenticationProvider
The filter above mixes two jobs: reading the header and deciding whether the token is valid. Spring Security's design separates them. The filter builds an unauthenticated token and hands it to the AuthenticationManager, and an AuthenticationProvider that supports that token type does the validation. We gain authentication success and failure events for auditing, credential erasure, a provider we can unit test without HTTP, and the option to reuse it from other entry points.
Taking this one step further, Spring Security's AuthenticationFilter with an AuthenticationConverter does the reading, delegating, context setting and failure handling for us, so we write only the converter and the provider.
6Follow-up questions
Why not continue the chain as anonymous when the token is invalid?
Because the result then depends on the URL rules. On a path that permits anonymous access, a caller with a forged or expired token would be let in without anyone noticing, and failures would never appear as authentication failures in logs or metrics. A failed attempt should fail loudly with 401.
Do we need to clear the context at the end of the request?
No. FilterChainProxy clears SecurityContextHolder in a finally block when the security chain finishes, so pooled request threads never keep our service identity. We only clear it ourselves on the failure path, before answering, so nothing downstream sees a half-set context.
Is a static shared token a good idea at all?
It is weak: it never expires, it is the same for every call, and anyone who sees it once can reuse it. It is acceptable as a transition step if tokens are per service, rotated and compared in constant time, but the long-term answer is client credentials tokens or mTLS workload identity.
7Conclusion
In this answer, we wrote a OncePerRequestFilter that continues when the X-Service-Token header is absent, sets a new authenticated SecurityContext through the SecurityContextHolderStrategy when it is valid, and clears the context and answers 401 through the entry point when it is not. We added it with addFilterBefore() relative to UsernamePasswordAuthenticationFilter or BearerTokenAuthenticationFilter, so it runs before authorization, avoided registering it twice as a servlet filter, and saw that delegating validation to an AuthenticationProvider gives a cleaner and more auditable design.
Open with
I'd extend OncePerRequestFilter and handle three cases. If there's no X-Service-Token header, the request isn't mine, so I just call chain.doFilter and return. If there is a header, I validate it, comparing in constant time.
Then, if they want more
If it's valid, I build an authenticated token, for example a PreAuthenticatedAuthenticationToken with the service name as principal, no credentials and an authority like SERVICE, create a new empty context through the SecurityContextHolderStrategy, set the authentication, set the context, and continue.
If it's invalid, I clear the context and call the AuthenticationEntryPoint so the caller gets 401, and I stop the chain, because silently continuing as anonymous could let a forged token through on a permitAll path.
For placement, it has to run before AuthorizationFilter, and conventionally among the authentication filters, so I use addFilterBefore with UsernamePasswordAuthenticationFilter, or BearerTokenAuthenticationFilter if the chain also takes JWTs. The class is only used as a position, so form login doesn't need to be enabled. The chain is stateless with CSRF off, and FilterChainProxy clears the context at the end.
One trap: if the filter is a @Component, Boot also registers it as a servlet filter and it runs twice, so I either create it in the config or add a FilterRegistrationBean with setEnabled false.
And in a real code base I'd go one step further: have the filter only extract the token and call the AuthenticationManager, with a provider doing the validation, which gives events, testability and reuse.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Spring Security 6
- 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 "Write a custom filter that authenticates requests carrying an X-Service-Token header...": https://scrivio-interview-library.netlify.app/spring-boot/security-architecture/7e2b1f6e8c/