问题
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.
回答1:
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.
回答2:
The most probable case is that some component in your code is calling HttpSession.invalidate()
while exception handling. You can easily find this out by a simple debugging.
But actually it is not necessary to check for isAnonymous()
- it is enough to check for user not having ROLE_USER
authority:
- In Spring Security 2: you can use
areNotGranted
attribute of<sec:authorize>
tag (see Spring Security 2 documentation - In Spring Security 3: you can use Spring EL for evaluation of negative condition:
access="!hasRole('ROLE_USER')"
来源:https://stackoverflow.com/questions/4780878/mapping-an-exception-to-404-page-while-using-spring-security-taglibs