Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping an exception to 404 page while using Spring Security taglibs

When mapping an Exception to 404 page, the Spring Security tags can't find the authentication information from the security context. With a "real" 404 the authentication is found.

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

On the JSP I have:

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

The /app/404 path is mapped to a controller which just returns the view. When I browse to /foo/some_invalid_id the NotFoundException gets thrown from the controller and finally when it goes to the JSP it can't find the authentication in SecurityContext and renders neither of the two options. Instead, when I'm browsing to /something_that_really_doesnt_exist it's able to figure out whether I'm logged in or not and renders the proper HTML.

like image 303
hleinone Avatar asked Jan 24 '11 10:01

hleinone


1 Answers

Add the following two dispatcher elements to your spring security filter-mapping:

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

By default only ordinary requests go through a defined filter-mapping.

"INCLUDE" and "FORWARD" are the two other valid dispatcher element values.

like image 151
applejack42 Avatar answered Sep 21 '22 18:09

applejack42