假设我有一个 main.jsp,其中包含另一个 protected 页面
<%
RequestDispatcher rd = request.getRequestDispatcher("secure/protected.jsp");
rd.include(request, response);
%>
<http auto-config="true" once-per-request="true">
<intercept-url pattern="/secure/**" access="ROLE_SUPERVISOR" />
....
</http>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
目前,我发现的是:
- Spring 安全过滤器实际上被调用。
- protected.jsp 仍然显示在 main.jsp 中。 (但我预计 protected.jsp 会被 Spring Security 阻止)
我读过相关讨论: Spring Security Allows Unauthorized User Access to Restricted URL from a Forward
是否可以保护包含的 jsp?如果没有,为什么? 我想原因是当我们使用请求调度程序时,我们仍然传递原始请求,因此Spring安全过滤器只知道原始请求路径(main.jsp)而不知道目标包含的路径(protectected.jsp)。因此,它不会阻止包含 protected.jsp
但它不起作用。 我使用 Spring security 3.1.2。
最佳答案
包含 JSP 基本上意味着将另一个 JSP 的内容内联到当前输出 (html) 文档中。 正如 san-krish 提到的,这些 JSP 包含不进行 servlet 过滤操作。
它们的主要目的是在您有可重用 JSP 时使用,例如用于导航或分页。
通常,它们不会被 servlet 容器公开。因此,它们应该位于 WEB-INF
下。
您没有透露有关您的申请的足够信息。但您似乎正在尝试路由到一个 JSP 内的不同页面。
将此视为设计缺陷。您的 View (JSP)应该只渲染模型数据,而您的 Controller (HttpServlet
或更好的 Spring MVC
请求处理程序)应该决定是否应该采用 JSP A 或 B渲染。
如果我的假设是错误的 - 抱歉产生噪音。
如果您尝试在登录后向用户显示不同的内容,您应该考虑实现自定义 AuthenticationSuccessHandler
它根据附加到 principal
的角色重定向到不同的 JSP。
如果您只想根据用户角色显示或隐藏页面内容,您应该利用 Spring Security's Taglib
:
在您的 pom.xml
中包含 Spring Security Taglib 工件(我认为 Maven 是理所当然的)。
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
将标记库添加到您的 JSP 中。
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags"%>
并用 authorize
标签包围 include
。更好的是,您应该将 authorize
移至 protected.jsp
以获得更好的可重用性。
<security:authorize ifAllGranted="ROLE_SUPERVISOR">
<jsp:include page="secure/protected.jsp" />
</security:authorize>
关于java - 如何使用 Spring security 保护包含的页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26115735/