advancedScenario Questions

Scenario 26: A method annotated with @Async that reads SecurityContextHolder.getContext().getAuthentication() gets null instead of the logged-in user.

By default, SecurityContextHolder uses a ThreadLocal strategy, so the authenticated context set on the original request thread isn't automatically visible to a new thread spawned by @Async. Fix by switching the holder strategy to MODE_INHERITABLETHREADLOCAL, or by explicitly capturing and propagating the SecurityContext into the async task yourself.

This is a Pro chapter

Sign in, then upgrade to Pro or Power to unlock this and the full Spring Ecosystem Mastery library.

Scenario 26: A method annotated with @Async that reads SecurityContextHolder.getContext().getAuthentication() gets null instead of the logged-in user.

Next Step

Continue to Scenario 27: After scaling from one server instance to three behind a load balancer, users report being logged out mid-session at random.← Back to all Spring Security questions