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

时间:2013-12-15 03:10:27

标签: java spring spring-mvc spring-security

我使用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)与带有斜杠的网址(例如/about/)不匹配,反之亦然。换句话说,具有斜杠的URL和没有斜杠的相同URL被Spring Security视为两个不同的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模式,但如果可能的话,我希望避免任何不必要的复杂性。

更新

正如Adam Gent所指出的,还有一个问题涉及带点的网址:/about.foo/about被Spring MVC视为相同的网址。但是,Spring Security将它们视为两个不同的URL。因此,可能还需要一个安全规则:

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

2 个答案:

答案 0 :(得分:15)

Spring Security 4.1 +

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

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

Java Config

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

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

XML配置

您需要将属性request-matcher添加到http标记:

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

Full Reference

请注意,您也不应该在角色前面添加&#34; ROLE _&#34;因为Spring Security会自动为您执行此操作。

4.1之前的Spring Security

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

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

Java Config

@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>

答案 1 :(得分:2)

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

在Spring Security 3.1.4中也适用于我。 这可以保护/about/about//about/anything_else

相关问题