Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

Compare writing a custom OncePerRequestFilter, using AuthenticationFilter with an AuthenticationConverter, and extending AbstractAuthenticationProcessingFilter for a new authentication method.

AuthenticationFilter with an AuthenticationConverter and an AuthenticationManager is the modern, composable choice for credentials sent on every request: the converter extracts credentials, a provider validates them, and success and failure handlers respond. AbstractAuthenticationProcessingFilter fits login endpoints that authenticate once on a specific URL and then redirect or create a session. A raw OncePerRequestFilter is the most flexible but leaves context handling, session saving, events and error handling to us. In Spring Security 6, saving the context to the session is explicit through a SecurityContextRepository, and authentication events are published through an AuthenticationEventPublisher for auditing.

Why this question is asked

Adding a new way to authenticate, an API key, a signed header, a one-time code, is one of the most common Spring Security tasks, and the framework offers three different starting points that all look reasonable. Picking the wrong one leads to familiar bugs: a login that is forgotten on the next request, an audit trail with no login events, errors that leak as 500s. Interviewers ask for the comparison because it shows whether we understand what each base class does for us. In this answer, we will recap the moving parts, look at each option with a short example, compare them side by side, and see how session saving and events affect the choice.

1A Quick Recap of the Moving Parts

Every authentication method in Spring Security has the same parts. Something reads credentials from the request. Something validates them, which by design is an AuthenticationProvider behind the AuthenticationManager. Something stores the result in the SecurityContext for this request, and, for logins that should be remembered, in a SecurityContextRepository such as the HTTP session. Something answers the client on success and failure. And something tells the rest of the system that a login happened, through authentication events.

The three options differ in how many of these parts they handle for us.

2Option 1: AuthenticationFilter With an AuthenticationConverter

AuthenticationFilter is a ready-made filter that takes two collaborators. The AuthenticationConverter turns a request into an unauthenticated Authentication, or returns null when the request carries no credentials. The AuthenticationManager validates it. The filter then sets the context, saves it through its SecurityContextRepository, and calls the success or failure handler.

Java
AuthenticationFilter filter = new AuthenticationFilter(
new ProviderManager(new SignedHeaderAuthenticationProvider(keys)), // validates
request -> { // AuthenticationConverter: extracts
String sig = request.getHeader("X-Signature");
return sig == null ? null : new SignedHeaderToken(sig, request.getHeader("X-Key-Id"));
});
filter.setSuccessHandler((req, res, auth) -> { }); // continue the chain
filter.setFailureHandler(new AuthenticationEntryPointFailureHandler(new HttpStatusEntryPoint(UNAUTHORIZED)));
http.addFilterBefore(filter, AuthorizationFilter.class);
// signed request -> authenticated, controller runs
// bad signature -> 401
// no header -> continues as anonymous

Notice how little we wrote: a lambda that reads headers and a provider that checks a signature. Each piece can be tested alone, and the provider can be reused by another filter. This is the composable approach and the default choice for credentials sent with every request.

3Option 2: AbstractAuthenticationProcessingFilter

AbstractAuthenticationProcessingFilter is the base class behind form login (UsernamePasswordAuthenticationFilter). It only acts on requests that match its matcher, for example POST /login/otp. There it calls our attemptAuthentication(), then runs the session authentication strategy (which changes the session id to prevent session fixation), sets and saves the context, triggers remember-me, publishes an interactive login event, and calls a success handler that typically redirects to the page the user wanted. Every other request passes through untouched.

Java
class OtpLoginFilter extends AbstractAuthenticationProcessingFilter {
OtpLoginFilter(AuthenticationManager manager) {
super("/login/otp", manager); // acts only on requests to this URL
setSecurityContextRepository(new HttpSessionSecurityContextRepository()); // remember the login
}
@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) {
return getAuthenticationManager().authenticate(
new OtpAuthenticationToken(req.getParameter("username"), req.getParameter("code")));
}
}
// POST /login/otp with a good code -> session id changed, context saved, 302 to the saved page
// GET /orders afterwards -> authenticated from the session

Notice the setSecurityContextRepository() call. When we add such a filter by hand rather than through a configurer, its default repository in version 6 only keeps the context for the current request, so without this line the user would be logged in for one request and anonymous on the next.

4Option 3: A Raw OncePerRequestFilter

A raw filter can do anything, which is both its strength and its risk. We read the header, validate, create the context, decide what happens on failure, and remember to stop the chain. Everything the other two options do for us becomes our responsibility: using a new context rather than changing a shared one, saving it if the login must last, mapping errors to 401 instead of exceptions leaking as 500, publishing events, and never letting a failed attempt continue as anonymous. It is still the right tool for things that are not really authentication, such as copying an already authenticated user into the MDC, or for very unusual protocols.

5Comparing the Options

Seen side by side, the choice usually follows from one question: is this a credential sent on every request, or a login that happens once and is then remembered?

Three ways to add an authentication method
AuthenticationFilter + converterAbstractAuthentication ProcessingFilterRaw OncePerRequestFilter
Best forCredentials on every request (keys, signatures)Login URL, then session or redirectUnusual cases, non-auth tasks
ValidationAuthenticationManager and providersAuthenticationManager and providersWhatever we write
Context and savingHandled; repository configurableHandled; set the session repositoryOurs to do, easy to forget
Session fixationNot applicable when statelessHandled by session strategyOurs to do
EventsProviderManager publishes themProvider events plus interactive loginNone unless we publish
Code we writeConverter and providerattemptAuthentication and providerEverything

6Saving the Context and Publishing Events

Two concerns cut across all three options. First, since Spring Security 6 nothing saves the SecurityContext automatically at the end of the request. Whoever authenticates must call securityContextRepository.saveContext() if the login must survive. The first two options do it through their repository property; a raw filter must do it by hand. For stateless credentials we deliberately keep the default request-scoped repository so no session is created.

Second, auditing. ProviderManager publishes AuthenticationSuccessEvent and failure events, such as AuthenticationFailureBadCredentialsEvent, through an AuthenticationEventPublisher. Spring Boot provides a DefaultAuthenticationEventPublisher bean, but a ProviderManager we construct ourselves does not use it unless we call setAuthenticationEventPublisher(). A raw filter that validates without any provider publishes nothing, so failed logins never reach the audit listener or the brute-force detection that relies on it.

Java
ProviderManager manager = new ProviderManager(new SignedHeaderAuthenticationProvider(keys));
manager.setAuthenticationEventPublisher(eventPublisher); // injected AuthenticationEventPublisher bean
@EventListener
void onFailure(AbstractAuthenticationFailureEvent e) {
audit.loginFailed(e.getAuthentication().getName(), e.getException().getClass().getSimpleName());
}
// failed signature -> audit row: loginFailed key-17 BadCredentialsException

7Follow-up questions

Can AuthenticationFilter be used for a login endpoint too?

Yes, with a request matcher, a session repository and a redirecting success handler it can behave like a login filter. But AbstractAuthenticationProcessingFilter already bundles session fixation protection, remember-me and the saved-request redirect, so for an interactive login it is usually less work and less risk.

Where does OAuth2 resource server fit in this comparison?

BearerTokenAuthenticationFilter is effectively a specialised version of the first option: a resolver extracts the bearer token, an AuthenticationManager with JwtAuthenticationProvider validates it, and failure goes to an entry point. That is a good sign the composable design is the one the framework itself prefers.

Should the provider check the account status too?

If the credential belongs to an account that can be disabled or locked, yes. Providers built on AbstractUserDetailsAuthenticationProvider do this automatically; a custom provider should throw DisabledException or LockedException so the right event and response follow.

8Conclusion

In this answer, we compared three ways to add an authentication method. AuthenticationFilter with an AuthenticationConverter and an AuthenticationManager splits extraction, validation and response into small, testable pieces and suits credentials sent on every request. AbstractAuthenticationProcessingFilter suits a login URL followed by a session or redirect, bundling session fixation protection and remember-me. A raw OncePerRequestFilter is flexible but leaves context handling, saving, events and errors to us. In version 6, saving is explicit through a SecurityContextRepository, and events flow through an AuthenticationEventPublisher.

What to say in the interviewAbout 100 seconds aloud

Open with

All three end up doing the same jobs: extract credentials, validate them, set the context, maybe save it, respond, and publish events. The difference is how much they do for me.

Then, if they want more

AuthenticationFilter with an AuthenticationConverter is the modern composable option: the converter turns the request into an unauthenticated token or null, the AuthenticationManager and a provider validate it, and the filter sets and saves the context and calls success and failure handlers.

I write a lambda and a provider, both easy to test, so it's my default for credentials sent on every request, like API keys or signed headers. AbstractAuthenticationProcessingFilter is the base of form login.

It acts only on its login URL, calls my attemptAuthentication, then applies session fixation protection, saves the context, handles remember-me and redirects to the saved request, so it fits interactive logins. One version 6 trap is that if I add it by hand I must set an HttpSessionSecurityContextRepository, or the login lasts one request.

A raw OncePerRequestFilter is flexible but everything is on me: new context, saving, 401 instead of 500, not continuing as anonymous on failure, and events.

On events, ProviderManager publishes success and failure events through an AuthenticationEventPublisher, but if I construct the manager myself I need to set the publisher, and a raw filter publishes nothing, which breaks auditing and brute-force detection. So I'd pick AuthenticationFilter for per-request credentials, the processing filter for logins, and the raw filter only for non-authentication tasks.

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 "Compare writing a custom OncePerRequestFilter, using AuthenticationFilter with an...": https://scrivio-interview-library.netlify.app/spring-boot/security-architecture/74a8fb5fed/