2011-01-24 20 views
9

將異常映射到404頁面時,Spring Security標記無法從安全上下文中找到認證信息。使用「真實」404,可以找到認證。在使用Spring Security標記庫時將異常映射到404頁面

我的web.xml:

<error-page> 
    <exception-type>com.example.NotFoundException</exception-type> 
    <location>/app/404</location> 
</error-page> 

<error-page> 
    <error-code>404</error-code> 
    <location>/app/404</location> 
</error-page> 

在JSP我:

<sec:authorize access="hasRole('ROLE_USER')"> 
    <%-- Show navigation links --%> 
</sec:authorize> 
<sec:authorize access="isAnonymous()"> 
    <%-- Show login form --%> 
</sec:authorize> 

/app/404路徑映射到控制器剛剛返回的視圖。當我瀏覽到/foo/some_invalid_id時,NotFoundException被從控制器拋出,最後當它進入JSP時,它無法在SecurityContext中找到身份驗證並呈現這兩個選項。相反,當我瀏覽到/something_that_really_doesnt_exist時,它能夠確定我是否登錄並呈現正確的HTML。

+0

這可能會幫助http://stackoverflow.com/questions/4153438/spring-security-issue-with-404-error – 2011-01-24 10:24:28

+0

謝謝,但它沒有幫助我。 – hleinone 2011-01-24 10:41:05

回答

17

添加以下兩個調度元素,以你的春季安全過濾器映射:

<filter-mapping> 
    ... 
    <dispatcher>REQUEST</dispatcher> 
    <dispatcher>ERROR</dispatcher> 
</filter-mapping> 

默認只有普通請求都通過一個定義的過濾器映射。

「INCLUDE」和「FORWARD」是另外兩個有效的調度程序元素值。

0

最有可能的情況是,代碼中的某些組件在調用異常時調用HttpSession.invalidate()。您可以通過簡單的調試輕鬆找到它。

但實際上它是沒有必要的檢查isAnonymous() - 這是足以檢查沒有用戶ROLE_USER權威:

  • 在Spring Security 2:你可以使用<sec:authorize>標籤areNotGranted屬性(見Spring Security 2 documentation
  • 在Spring Security 3:你可以使用Spring EL爲負狀況評估:access="!hasRole('ROLE_USER')"
+0

我在Spring Security 3上,所以我可以使用否定,但是我猜想即使用戶已經登錄,它總會呈現登錄表單,因爲正確的數據不在那裏。 – hleinone 2011-01-24 15:49:19

相關問題