liveBook · Manning

MODE_INHERITABLETHREADLOCAL

As explained in Spring Security in Action, Second Edition

MODE_INHERITABLETHREADLOCAL is a Spring Security security-context strategy mode that makes a thread's context available to child threads through inheritable thread-local storage.

MODE_INHERITABLETHREADLOCAL makes Spring Security copy the requesting thread’s security context into a child thread used by an asynchronous method. section 6.2

Configure the strategy through either supported mechanism:

  • Call SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL). section 6.2.2
  • Set the spring.security.strategy system property. section 6.2.2
  • Use it when Spring creates the asynchronous thread, such as for an @Async method; it does not automatically cover application-created threads. section 6.2.2 section 6.4

Configuring asynchronous context inheritance

A configuration bean can set the mode during initialization: return () -> SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);. An @Async endpoint can then read context.getAuthentication().getName() without receiving a null Authentication. section 6.2.2

Listing 6.10 Using InitializingBean to set SecurityContextHolder mode
@Configuration
@EnableAsync
public class ProjectConfig {

  @Bean
  public InitializingBean initializingBean() {
    return () -> SecurityContextHolder.setStrategyName(
      SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
  }
}

Shows the Java configuration that sets MODE_INHERITABLETHREADLOCAL with InitializingBean. section 6.2.2

How Spring Security in Action, Second Edition covers it

How deep it goes
Explains strategy behavior and configuration, but stops short of automatic propagation to application-created threads.
Examples
Uses an @Async goodbye endpoint, Authentication access, InitializingBean configuration, and a context-propagation figure.
What it assumes
Assumes basic SecurityContext and Authentication knowledge while showing how asynchronous execution changes context availability.
What you can do after
Configure it via SecurityContextHolder or the spring.security.strategy system property for Spring-managed asynchronous methods.
How it connects
Connects SecurityContextHolder, SecurityContext, Authentication, @Async, and MODE_THREADLOCAL.

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.