为什么Spring Security身份验证为null

时间:2014-05-27 14:04:18

标签: spring-mvc spring-security

我的Tomcat下有以下网站(都使用Spring MVC)

www.example.com (anyone can access)
www.example.com/member (only authenticated user)

和我在HTTPErrorController中的方法

@RequestMapping(value = "/errors/404.html")
    public String handle404(HttpServletRequest request, Exception e) {
        logger.error(e.getMessage());
        Authentication authentication = SecurityContextHolder.getContext()
                .getAuthentication();
        return authentication == null ? defaultPage : defaultAuthorizedPage;
        // return defaultAuthorizedPage;
    }

Spring Security

<intercept-url pattern="/*" access="hasAnyRole('ROLE_USER', 'ROLE_ADMIN','ROLE_ANONYMOUS')"
            requires-channel="https" />
<intercept-url pattern="/member/**" access="isFullyAuthenticated()"
            requires-channel="https" />

现在,如果用户已登录并尝试访问不存在的页面,则应将其重定向到www.example.com/member/home(默认授权页面),而普通用户/来宾应重定向到主页www.example.com/home (默认页面)。

问题是身份验证始终为null,因此我无法确定用户是否已记录。我该怎么办呢?

1 个答案:

答案 0 :(得分:1)

如果希望保护容器管理的错误页面/包含Spring Security的SecurityContext,则需要确保包含springSecurityFilterChain的ERROR请求调度程序。例如,web.xml中的以下内容

<filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
  <dispatcher>REQUEST</dispatcher>
  <dispatcher>ERROR</dispatcher>
</filter-mapping>