2016-07-05 31 views
1

我有一个Spring Boot应用程序,我使用的是Spring Security(4.0.4)。Spring Security 4:如何忽略尾部斜杠

端点的当前安全配置(以Java为单位)允许调用/some/endpoint,但不允许调用/some/endpoint/

我已经在这里搜索过,但我没有看到任何东西像开关忽略尾随空格。例如,Spring MVC的,我可以做到以下几点:

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

当然,上面的代码改变了我想要的行为相反的,但它只是作为的想什么我做示范Spring Security。

我的(减少)的安全配置:

@Bean 
public ResourceServerConfigurer resourceServerConfigurer(final ScopesProperties oauthProperties) { 
    return new ResourceServerConfigurerAdapter() { 
     @Override 
     public void configure(final HttpSecurity http) throws Exception { 
      http.sessionManagement().sessionCreationPolicy(NEVER).and() 
        .authorizeRequests() 
        .antMatchers(GET, "/foo") 
        .access(oauthProperties.getFooRead()) 
        .antMatchers(GET, "/bar/*") 
        .access(oauthProperties.getBarRead()) 
        .antMatchers(PUT, "/bar/*") 
        .access(oauthProperties.getBarWrite()) 
        // everything else 
        .anyRequest().denyAll(); 
     } 

我知道我可以使用正则表达式匹配器,我想避免的,主要是出于同样的原因它,因为我想避免一个额外的规则为每个端点只是批准具有结尾斜杠的同一端点。我必须为每个端点执行此操作,这很容易出错。我也知道我可以使用ant匹配器并将路径设置为/foo/**。与此问题是当我想控制不同范围的子资源。

所以问题是:如何告诉Spring Security全局忽略尾随斜线?

在此先感谢

回答

1

万一有人有同样的问题,是它的一个解决方案。这就是所谓的MvcRequestMatcher,你可以在Spring Documentation

阅读所有关于它的下面是主要部分:

的问题是,我们的安全规则只保护/管理。我们可以为Spring MVC的所有排列添加额外的规则,但这将是非常冗长和乏味的。

相反,我们可以利用Spring Security的MvcRequestMatcher。以下配置将通过使用Spring MVC匹配URL来保护Spring MVC将匹配的相同URL。

下面是配置如何看现在:

@Bean 
public ResourceServerConfigurer resourceServerConfigurer(final ScopesProperties oauthProperties) { 
    return new ResourceServerConfigurerAdapter() { 
     @Override 
     public void configure(final HttpSecurity http) throws Exception { 
      http.sessionManagement().sessionCreationPolicy(NEVER).and() 
       .authorizeRequests() 
       .mvcMatchers(GET, "/foo") 
       .access(oauthProperties.getFooRead()) 
       .mvcMatchers(GET, "/bar") 
       .access(oauthProperties.getBarRead()) 
       .mvcMatchers(PUT, "/bar") 
       .access(oauthProperties.getBarWrite()) 
       // everything else 
       .anyRequest().denyAll(); 
    }