我已经在这个问题上挣扎了一段时间。找到了几个关于它的帖子,但没有一个解决了我的问题。它可能与 SecurityContext 与特定线程相关的事实有关,但即使如此我也不知道如何解决它:
考虑以下代码来检索登录的用户:
SecurityContextHolder.getContext().getAuthentication().getPrincipal()
在 Controller 中运行此代码将返回(正确)用户登录。
从 taglib 或 jsp 运行此代码会引发 NPE(身份验证 = null)。
还有 Spring 标签 不起作用(大概是出于同样的原因)。
从 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>
最佳答案
解决
问题来自过滤器序列。 PageFilter (sitemesh) 在 spring 安全过滤器之前被调用,因此安全上下文在 jsp 中尚不可用。更改 web.xml 中过滤器的顺序(首先是安全过滤器)修复了该问题。
关于security - Spring 安全性 - SecurityContext.authentication 在 taglib 和 jsp 中为 null,但在 Controller 中还可以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1572232/