使用 Spring Security 标记库时将异常映射到 404 页面
将异常映射到 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< 中找到身份验证/code> 并不会呈现这两个选项。相反,当我浏览到
/something_that_really_doesnt_exist
时,它能够确定我是否已登录并呈现正确的 HTML。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将以下两个调度程序元素添加到您的 spring security 过滤器映射中:
默认情况下,只有普通请求才会经过定义的过滤器映射。
“INCLUDE”和“FORWARD”是另外两个有效的调度程序元素值。
Add the following two dispatcher elements to your spring security filter-mapping:
By default only ordinary requests go through a defined filter-mapping.
"INCLUDE" and "FORWARD" are the two other valid dispatcher element values.
最可能的情况是代码中的某些组件在异常处理时调用
HttpSession.invalidate()
。通过简单的调试就可以轻松发现这一点。但实际上没有必要检查
isAnonymous()
- 检查用户是否没有ROLE_USER
权限就足够了:
标记的areNotGranted
属性(请参阅 Spring Security 2 文档access="! hasRole('ROLE_USER')"
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 havingROLE_USER
authority:areNotGranted
attribute of<sec:authorize>
tag (see Spring Security 2 documentationaccess="!hasRole('ROLE_USER')"