How to set up Spring Security SecurityContextHolder strategy?

Viewed 44097

I'm using asynchronous methods in my service (Spring 3 @Async annotation). And I've got a problem - spawned thread doesn't have security context. Cause of it is Spring Security by default uses SecurityContextHolder.MODE_THREADLOCAL strategy for its context holder. But I need to use SecurityContextHolder.MODE_INHERITABLETHREADLOCAL strategy. For the moment I set up strategy in my AuthenticationSuccessHandler. But in my point of view it's not a good practice.

So how can I set it up in context configuration file?
Version of spring security is 3.0.0.

4 Answers

Via Java configuration without reflection.

import javax.annotation.PostConstruct;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.context.SecurityContextHolder;

@Configuration
public class SecurityConfig {

  @PostConstruct
  public void enableAuthCtxOnSpawnedThreads() {
    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
  }
}
Related