How to set up Spring Security SecurityContextHolder strategy?

Solution 1:

You can set the environment variable spring.security.strategy to MODE_INHERITABLETHREADLOCAL. You could also have a simple bean that during your web applications startup calls SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL) and initialize that value in your context configuration file.

SecurityContextHolder API

Solution 2:

The java config for @viator 's answer if it helps you.

@Bean
public MethodInvokingFactoryBean methodInvokingFactoryBean() {
    MethodInvokingFactoryBean methodInvokingFactoryBean = new MethodInvokingFactoryBean();
    methodInvokingFactoryBean.setTargetClass(SecurityContextHolder.class);
    methodInvokingFactoryBean.setTargetMethod("setStrategyName");
    methodInvokingFactoryBean.setArguments(new String[]{SecurityContextHolder.MODE_INHERITABLETHREADLOCAL});
    return methodInvokingFactoryBean;
}

Solution 3:

A little bit another solution, like @viator write:

<bean
        class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetClass"
            value="org.springframework.security.core.context.SecurityContextHolder" />
        <property name="targetMethod" value="setStrategyName" />
        <property name="arguments" value="MODE_INHERITABLETHREADLOCAL" />
    </bean>

Working like a charm.

Solution 4:

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);
  }
}