MODE_THREADLOCAL stores Spring Security’s SecurityContext in JDK ThreadLocal storage. Each request thread sees its own Authentication, making this the default strategy for traditional servlet applications. section 6.2.1 section 6.2
Use the strategy with these boundaries in mind:
- Access the authenticated identity through SecurityContextHolder.getContext().getAuthentication() after authentication succeeds. section 6.2.1 section 6.2
- Expect an asynchronous method on another thread to lack the parent request’s context; MODE_THREADLOCAL does not copy it. section 6.2.2
- Prefer MODE_INHERITABLETHREADLOCAL when asynchronous execution must inherit context, or use Spring Security delegation utilities for application-created threads. section 6.2.2 section 6.4
Reading the current authentication
A controller can obtain the request’s isolated context and use its authentication: SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = context.getAuthentication(); return "Hello, " + authentication.getName() + "!";
Figure 6.8 Each request has its own thread represented by an arrow. Each thread has access only to its own security context details. When a new thread is created (for example, by an @Async method), the details from the parent thread aren’t copied.
Visualize request-to-thread isolation and why a newly created asynchronous thread does not receive the parent context. section 6.2.1
