SecurityContextHolder.getContext()在AspectJ类中不起作用

Vik*_*ram 3 aop spring spring-security

我创建了一个@Aspect类,并尝试获取主要对象,如...

SecurityContextHolder.getContext().getAuthentication() .getPrincipal()
Run Code Online (Sandbox Code Playgroud)

在我的方面类中,但我得到空指针.在我的方面没有可用的上下文.任何指针.?

Vir*_*gic 7

SecurityContextHolder将给定的SecurityContext与当前执行线程相关联.由于方面在单独的线程上截获方法(不太确定),因此您可能需要更改安全上下文持有者策略.由于SecurityContextHolder提供了一系列委托给SecurityContextHolderStrategy实例的静态方法.SecurityContextHolder的目的是提供一种方便的方法来指定应该用于给定JVM的策略.

如果没有定义策略,SecurityContextHolder类将默认使用MODE_THREADLOCAL.

因此,您需要将策略更改为MODE_INHERITABLETHREADLOCAL.

有两种方法可以指定所需的策略模式.第一种是通过SYSTEM_PROPERTY上键入的系统属性来指定它.第二种是在使用该类之前调用setStrategyName(String) .

在Spring中,您需要在应用程序上下文中定义bean,如下所示:

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetClass"><value>org.springframework.security.core.context.SecurityContextHolder</value></property>
    <property name="targetMethod"><value>setStrategyName</value></property>
    <property name="arguments">
        <list>
            <value>MODE_INHERITABLETHREADLOCAL</value>
        </list>
    </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

  • 我如何使用 @Bean 以编程方式配置这个答案? (2认同)