gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:42:07 25 4
gpt4 key购买 nike

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

SecurityContextHolder.getContext().getAuthentication() .getPrincipal()

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

最佳答案

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

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

因此需要将策略更改为 MODE_INHERITABLETHREADLOCAL。

有两种方法可以指定所需的策略模式。第一种是通过 SYSTEM_PROPERTY 上键入的系统属性来指定它。第二个是调用 setStrategyName(String) before using the class

在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>

关于spring - SecurityContextHolder.getContext() 在 AspectJ 类中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18229619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com