SecurityContextHolder manages access to the SecurityContext, which stores the authenticated entity’s Authentication after successful authentication. In a thread-per-request application, each request commonly receives its own context. section 6.2 section 6.2.1
Choose the strategy according to how execution is organized:
- MODE_THREADLOCAL keeps context details isolated per thread and suits independent web requests. section 6.2
- MODE_INHERITABLETHREADLOCAL copies context details to framework-created asynchronous threads, such as those used by @Async. section 6.2.2
- MODE_GLOBAL shares one context across application threads, fitting some standalone applications but requiring concurrency care. section 6.2.3
Reading the authenticated user
An endpoint can call SecurityContextHolder.getContext(), obtain Authentication, and return its name. Spring can instead inject Authentication directly into the endpoint parameter. An @Async method requires an inheritable strategy; application-created threads require explicit context copying. section 6.2.1 section 6.2.2
