【问题标题】:Web.xml security constraint on context-root doesn't apply上下文根上的 Web.xml 安全约束不适用
【发布时间】:2025-11-23 10:25:02
【问题描述】:

我有一个使用 web.xml 来配置其安全性的 java webapp:

<security-constraint>
    <web-resource-collection>
        <web-resource-name>webPages</web-resource-name>
        <description>All web resources</description>
        <url-pattern></url-pattern>
        <url-pattern>/admin/*</url-pattern>
        <http-method>POST</http-method>
        <http-method>GET</http-method>
    </web-resource-collection>
    <auth-constraint>
        <role-name>admins</role-name>
    </auth-constraint>
    <user-data-constraint>
        <description>SSL not required</description>
        <transport-guarantee>NONE</transport-guarantee>
    </user-data-constraint>
</security-constraint>

我希望 /admin/* 下的所有页面都受到保护,这很有效。用户正确地首先看到一个登录屏幕,然后被重定向到原始请求的页面。

我还希望我的上下文根受到保护:http://host:port/context/ 但是,当我配置模式 &lt;url-pattern&gt;&lt;/url-pattern&gt; 并向根发出请求时,我的 java 控制器开始工作并显示视图,而用户从未看到登录屏幕。为什么这种模式适用于 &lt;servlet-mapping&gt;(将请求映射到 spring servlet)之类的东西,而不是作为安全约束?

我在 chrome 和 firefox 中都尝试过,并多次重启。

【问题讨论】:

  • 您是否使用 /* 进行根上下文配置?
  • @aksappy 不,因为 /* 作为 url 模式意味着“捕获所有请求”,我不想要那个,只有根上下文。例如,/otherpage.do 应该在没有授权的情况下继续工作。
  • 按照规范,你做的是对的。

标签: java servlets jboss web.xml security-constraint


【解决方案1】:

您可以尝试白名单的方法,这意味着只允许访问公共资源。

Here is a better answer 以示例为例,但在您的情况下应该是这样的:

<security-constraint>
  <web-resource-collection>
    <web-resource-name>webPages</web-resource-name>
    <description>All web resources</description>
    <url-pattern>/</url-pattern>
    <http-method>POST</http-method>
    <http-method>GET</http-method>
  </web-resource-collection>
  <auth-constraint>
    <role-name>admins</role-name>
  </auth-constraint>
  <user-data-constraint>
    <description>SSL not required</description>
    <transport-guarantee>NONE</transport-guarantee>
  </user-data-constraint>
</security-constraint>
<security-constraint>   
  <web-resource-collection>
    <web-resource-name>Public Resources</web-resource-name>
    <url-pattern>/public/*</url-pattern>
    <url-pattern>/alsopublic</url-pattern>
    <url-pattern>...an so on...</url-pattern>
  </web-resource-collection>  
  <!-- to given public access don't set auth-constraint-->
</security-constraint>

编辑: 参考servlet 3 specification

【讨论】:

  • 这不起作用。服务器正确地知道根现在是“安全的”,但是当它尝试重定向到位于 /login.do 的登录页面时,我认为这个请求被阻止了。几秒钟后,我在服务器上收到一条错误消息,指出已创建最大线程数,这表示无限循环。此外,您指向 servlet 3 规范的链接对我不起作用:我似乎无权执行该请求。
  • 我不明白您的评论:¿/ 只按应有的方式保护根目录?还要指定 /login.do 在用户登录后做什么(例如重定向)。
  • 通过声明 /,它还保护了我所有的其他内容,而不仅仅是根。我认为这 / 不是描述上下文根的正确方法。根据 servlet 3.0,正确的 url 模式是空字符串。