A security context stores the Authentication associated with the current execution or request. After successful authentication, the filter places this data in the context, where controllers and authorization logic can use it until the action ends. section 2.2 section 6.2
Figure 6.7 After successful authentication, the authentication filter stores the details of the authenticated entity in the security context. From there, the controller implementing the action mapped to the request can access these details when needed.
Follow the request flow from successful authentication to controller access through the security context. section 6.2
Access the context through SecurityContextHolder and choose a strategy that matches the execution model:
- MODE_THREADLOCAL keeps separate context details for each thread and suits the usual thread-per-request web application. section 6.2
- MODE_INHERITABLETHREADLOCAL copies the context to a child thread, supporting asynchronous methods such as those annotated with @Async. section 6.2 section 6.2.2
- MODE_GLOBAL exposes one context to every thread, which can fit standalone applications but requires care with concurrent access and synchronization. section 6.2.3
Reading authentication in an asynchronous method
An @Async method can obtain the current username with SecurityContextHolder.getContext().getAuthentication().getName(). Without an inheritable strategy, the worker thread may have no authentication and cause a NullPointerException; configure MODE_INHERITABLETHREADLOCAL when the execution model requires propagation. section 6.2.2
Method-security tests can define a SecurityContext with @WithMockUser, @WithUserDetails, or a custom annotation, then invoke the secured bean directly without MockMvc. section 18.4



