我一直在努力解决这个问题一段时间。找到了几篇关于它的帖子,但没有一个能解决我的问题。这可能与 SecurityContext 与特定线程有关,但即便如此我也不知道如何解决它:
考虑以下代码来检索已登录的用户:
SecurityContextHolder.getContext().getAuthentication().getPrincipal()
在控制器中运行此代码将(正确)返回用户登录。从 taglib 或 jsp 运行此代码会引发 NPE(身份验证 = null)。还有弹簧标签不起作用(可能出于相同的原因)。
从 web.xml 中提取:
<filter>
<filter-name>AcegiFilter</filter-name>
<filter-class>org.acegisecurity.util.FilterToBeanProxy</filter-class>
<init-param>
<param-name>targetClass</param-name>
<param-value>org.acegisecurity.util.FilterChainProxy</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>AcegiFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
从 spring 安全配置文件中提取:
<bean id="filterChainProxy" class="org.springframework.security.util.FilterChainProxy">
<property name="filterInvocationDefinitionSource">
<value>
CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
PATTERN_TYPE_APACHE_ANT
/**=httpSessionIntegrationFilter,authenticationProcessingFilter,exceptionTranslationFilter,filterSecurityInterceptor
</value>
</property>
</bean>
<bean id="filterSecurityInterceptor"
class="org.springframework.security.intercept.web.FilterSecurityInterceptor">
<property name="authenticationManager" ref="authenticationManager" />
<property name="accessDecisionManager" ref="accessDecisionManager" />
<property name="alwaysReauthenticate" value="true" />
<property name="objectDefinitionSource">
<value>
CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
PATTERN_TYPE_APACHE_ANT
/myaccount.htm=ROLE_CUSTOMER
</value>
</property>
</bean>