liveBook · Manning

Mode_threadlocal

As explained in Spring Security in Action, Second Edition

MODE_THREADLOCAL is a SecurityContextHolder strategy mode that stores the security context in the current thread's local storage.

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

How Spring Security in Action, Second Edition covers it

How deep it goes
Explains ThreadLocal isolation, SecurityContextHolder access, and asynchronous limitations, but defers reactive applications.
Examples
Demonstrates a controller reading Authentication through SecurityContextHolder and contrasts it with an @Async endpoint.
What it assumes
Assumes basic Spring and Java knowledge while defining SecurityContext storage and request-thread isolation.
What you can do after
Operate request-scoped authentication access through SecurityContextHolder and recognize when asynchronous execution requires another strategy.
How it connects
Connects SecurityContext, Authentication, SecurityContextHolder, asynchronous execution, and MODE_INHERITABLETHREADLOCAL.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Security in Action, Second Edition. The section links point to the parts of the book it draws on.