Spring Security,URL中的尾部斜杠和点


问题内容

我使用Spring Security 3.1.4保护部署到Tomcat的Spring MVC 3.2.4应用程序。我具有以下Spring
Security配置:

<http auto-config="true" use-expressions="true">
   <http-basic />
   <logout ... />
   <form-login ... />

   <intercept-url pattern="/" access="isAnonymous() or hasRole('ROLE_USER')" />
   <intercept-url pattern="/about" access="isAnonymous() or hasRole('ROLE_USER')" />
   <intercept-url pattern="/login" access="isAnonymous() or hasRole('ROLE_USER')" />
   <intercept-url pattern="/under-construction" access="isAnonymous() or hasRole('ROLE_USER')" />
   <intercept-url pattern="/admin-task*" access="hasRole('ROLE_USER') and hasRole('ROLE_ADMINISTRATOR')" />
   <intercept-url pattern="/resources/**" access="isAnonymous() or hasRole('ROLE_USER')" />
   <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
</http>

我注意到没有尾部斜杠(例如/about)的URL模式与具有尾部斜杠(例如/about/)的URL不匹配,反之亦然。换句话说,Spring
Security将带有斜杠的URL和没有斜杠的相同URL视为两个不同的URL。可以通过使用两个安全规则来解决此问题:

<intercept-url pattern="/about" access="isAnonymous() or hasRole('ROLE_USER')" />
<intercept-url pattern="/about/" access="isAnonymous() or hasRole('ROLE_USER')" />

有更好的解决方案吗?

我知道path-type="regex"可以用正则表达式定义URL模式,但是我想避免任何不必要的复杂性。

更新资料

正如亚当·根特指出,有可能涉及到的网址以点另外一个问题:/about.foo/about被视为由Spring
MVC相同的URL。但是,Spring Security将它们视为两个不同的URL。因此,可能还需要一个安全规则:

<intercept-url pattern="/about.*" .../>

问题答案:

Spring Security 4.1+

Spring Security现在添加了一个新的匹配器,该匹配器知道您的Spring MVC URL匹配配置。这告诉Spring
Security根据与Spring MVC使用的相同规则来匹配路径,从而消除了URL有效但不安全的可能性。

首先,您需要用新的MVC匹配器替换所有旧的匹配器。Spring Security现在可以与之同步,但是您已经配置了Spring
MVC,因此可以自由添加或删除任何路径匹配的配置。我建议尽可能使用默认值。

Java配置

如果您正在使用antMatchers,现在应该使用mvcMatchers

protected configure(HttpSecurity http) throws Exception {
  http.authorizeRequests()
        .mvcMatchers("/about").hasRole("USER");
}

XML配置

您需要将属性添加request-matcherhttp标签中:

<http request-matcher="mvc">
  <intercept-url pattern="/about" access="hasRole('USER')"/>
</http>

完整参考

请注意,您也不应再为角色添加“ ROLE”前缀,因为Spring Security会自动为您这样做。_


4.1之前的Spring Security

我无法找到一种在Spring
Security中处理尾部斜杠和路径后缀的方法。显然,可以编写一个正则表达式来处理这些情况,但这似乎使安全规则过于复杂并易于出错。我想尽可能地确信自己不会意外暴露资源。

因此,我的方法是通过将路径匹配器配置为对尾随斜杠和后缀都严格,来禁用Spring中的此行为。

Java配置

@Configuration
public class ServletConfig extends WebMvcConfigurerAdapter {
  @Override
  public void configurePathMatch(final PathMatchConfigurer configurer) {
    configurer.setUseSuffixPatternMatch(false);
    configurer.setUseTrailingSlashMatch(false);
  }
}

XML配置

<mvc:annotation-driven>
  <mvc:path-matching suffix-pattern="false" trailing-slash="false" />
</mvc:annotation-driven>