Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A tracing filter and a request-logging filter in your service need the authenticated user's id, but they log null for every request. How would you find out why and fix it?

The two filters most likely run before the Spring Security filter in the servlet filter order, or read the user after the security chain has already cleared it, so SecurityContextHolder is empty when they look. We confirm it by comparing their orders with spring.security.filter.order (-100 by default), then fix it by reading the user in a small filter placed after authentication, either ordered after -100 or added inside the security chain with addFilterAfter, and putting the user id into the MDC and the current observation from there.

Why this question is asked

A log line or a trace without the user id is a small thing until we need it: a customer reports an error and we cannot find their requests, or a security review asks who called an endpoint. Interviewers ask this scenario because the fix is simple once we understand that filters run in one ordered list and that the security context only exists for part of it. In this answer, we will recap where the user lives during a request, find out why these filters see null, look at how to confirm it, and then fix it in a way that keeps the tracing filter's timing correct.

1A Quick Recap of Where the User Lives

Spring Security keeps the current user in SecurityContextHolder, which by default stores a SecurityContext in a ThreadLocal, a variable that has a separate value for each thread. The context is filled by the authentication filters inside the security filter chain, for example BearerTokenAuthenticationFilter for a JWT, and it is cleared by FilterChainProxy in a finally block when the chain returns.

All of Spring Security sits behind one servlet filter, DelegatingFilterProxy, which Boot registers at order -100. Every other servlet filter in the application, including our tracing and logging filters, has its own place in the same ordered list. So there is a window: before the security filter the user does not exist yet, inside it the user is set, and after the security filter returns the user has been removed again.

2Why These Two Filters See Null

The usual tracing filter is Spring's ServerHttpObservationFilter, which Boot registers at Ordered.HIGHEST_PRECEDENCE + 1 on purpose: it wants to time the whole request, so it starts first. Request-logging filters are often given a high precedence too, so they can log every request including rejected ones. Both therefore run before -100, when no authentication exists.

There is a second trap. A logging filter often writes its line after chain.doFilter() returns, so it can include the status and duration. Even if it wraps the security filter, by then FilterChainProxy has already cleared SecurityContextHolder. So the filter is reading at the wrong time as well as from the wrong place.

Java
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 10) // runs before Spring Security (-100)
class RequestLogFilter extends OncePerRequestFilter {
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
log.info("start user={}", currentUserId()); // start user=null: nobody authenticated yet
chain.doFilter(req, res);
log.info("end user={} status={}", currentUserId(), res.getStatus());
// end user=null status=200: context already cleared
}
}
Step throughWhen the user exists during one request
Logging filterSpring SecurityController
read user: null, not authenticated yet
chain.doFilter()
authenticate, set SecurityContextHolder
controller runs, user is visible
returns
finally: clear SecurityContextHolder
returns
read user again: null, already cleared

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

The user exists only between authentication and the end of the security chain.

Notice that the request was authenticated and succeeded, yet both lines print null. Nothing is broken in Spring Security; the filter simply looks at the user outside the window in which it exists.

3Confirming the Order

We do not have to guess. The quickest check is a breakpoint in the logging filter: if FilterChainProxy is not in the call stack above it, the filter runs outside Spring Security. We can also turn on logging.level.org.springframework.security=TRACE and see whether the line Securing GET /orders appears before or after the filter's own log line.

Then we compare the numbers. Spring Security's position comes from spring.security.filter.order. Our filters get theirs from @Order, from Ordered, or from a FilterRegistrationBean with setOrder(). A filter bean without any order gets Ordered.LOWEST_PRECEDENCE, which runs after security, so if a filter sees null, someone usually gave it a high precedence on purpose, and we should find out why before moving it.

4Fix: Read the User Inside the Window

The clean fix is not to move the tracing filter. It must stay early to measure the full request. Instead we add one small filter that runs after authentication, reads the user once, and writes it to the places the other filters read from: the MDC (the logging library's per-thread map of values that appear in every log line) and the current observation (Micrometer's record of this request, which becomes the trace span).

Java
class UserContextFilter extends OncePerRequestFilter {
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String userId = (auth != null && auth.isAuthenticated()
&& !(auth instanceof AnonymousAuthenticationToken)) ? auth.getName() : "anonymous";
MDC.put("userId", userId); // every log line now has it
req.setAttribute("userId", userId); // for filters that log after the chain
ServerHttpObservationFilter.findObservationContext(req)
.ifPresent(ctx -> ctx.addHighCardinalityKeyValue(KeyValue.of("user.id", userId))); // on the span
try {
chain.doFilter(req, res);
} finally {
MDC.remove("userId"); // threads are reused
}
}
}
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(a -> a.anyRequest().authenticated())
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
.addFilterAfter(new UserContextFilter(), BearerTokenAuthenticationFilter.class);
return http.build();
}
// log: start ... userId=7f3a (any line written inside the chain)
// trace span tag: user.id=7f3a

Notice three details. We add the filter inside the security chain with addFilterAfter, right after the authentication filter, so it always runs after the user is set. We put the id on the observation as a high-cardinality value, which goes to the trace but not to metrics, because a metric label per user would explode the number of time series. And we store it as a request attribute, so the early logging filter can read it after chain.doFilter() returns, when SecurityContextHolder is already empty.

The alternative is to keep a normal servlet filter and order it after the security filter, for example with a FilterRegistrationBean at order -99 or the default lowest precedence. That works too, but the filter then lives outside the chain, and if we change spring.security.filter.order later it can silently move to the wrong side.

5Making the Early Logging Filter Use It

The request-logging filter can stay where it is if it reads the request attribute instead of SecurityContextHolder at the end of the request. The start line will still have no user, which is honest, because at that point nobody is authenticated. If the start line must contain the user, the filter itself has to move after authentication.

Java
chain.doFilter(req, res);
log.info("end user={} status={}", req.getAttribute("userId"), res.getStatus()); // end user=7f3a status=200

6Follow-up questions

Why not just give the logging filter a lower precedence than -100 and be done?

For a pure logging filter that is fine. For the tracing filter it is wrong, because the observation would then start after security, and the time spent authenticating, plus every request rejected with 401 or 403, would be missing from traces. That is why we enrich the existing observation from a filter inside the window instead of moving the observation filter.

The user id is still missing on log lines written by an @Async method. Why?

MDC and SecurityContextHolder are both ThreadLocal values, so they stay on the request thread. Work handed to another thread needs them copied, for example with a TaskDecorator that captures the MDC map and the security context and restores them in the task, or with DelegatingSecurityContextAsyncTaskExecutor plus Micrometer's context propagation.

Is it safe to put the user id in traces and logs?

Usually an internal user id is acceptable, but an email address or name is personal data that then spreads to every log store. We log a stable internal id, never tokens or credentials, and we check the retention and access rules of the tracing backend, because traces are often kept and shared more widely than application logs.

7Conclusion

In this answer, we saw that the user only exists in SecurityContextHolder between authentication and the end of the security filter chain. The tracing and logging filters ran before that window, and the logging filter also read after the chain had cleared the context, so both saw null. We confirmed the order by comparing @Order and FilterRegistrationBean values with spring.security.filter.order, and fixed it with a small filter added after the authentication filter that writes the user id to the MDC, the current observation and a request attribute.

What to say in the interviewAbout 90 seconds aloud

Open with

My first suspicion would be filter order, not Spring Security. All servlet filters run in one ordered list, and Spring Security sits in it at spring.security.filter.order, which is -100 by default.

Then, if they want more

The tracing filter, ServerHttpObservationFilter, runs at highest precedence on purpose, and logging filters are often ordered high too, so both run before anybody is authenticated and SecurityContextHolder is empty. There is a second trap: a logging filter that writes its line after chain.doFilter returns is too late, because FilterChainProxy clears the context in a finally block when the chain finishes.

To confirm, I'd put a breakpoint in the filter and check whether FilterChainProxy is in the stack, or turn on security TRACE logging and compare the order of the lines, and then compare the @Order and FilterRegistrationBean values with -100.

For the fix, I would not move the tracing filter, because it needs to time the whole request including rejected ones. Instead I'd add one small filter inside the security chain with addFilterAfter, right after the authentication filter.

It reads the user once, puts the id into the MDC so every log line has it, adds it to the current observation as a high-cardinality value so it reaches the span but not the metrics, and stores it as a request attribute so the early logging filter can read it at the end. It removes the MDC entry in a finally block, because threads are reused.

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 "A tracing filter and a request-logging filter in your service need the authenticated...": https://scrivio-interview-library.netlify.app/spring-boot/security-architecture/5a01e411bf/