How to set up Spring Security SecurityContextHolde

2019-01-11 00:58发布

问题:

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.

回答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



回答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;
}


回答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.