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
