我有一个Spring应用程序,我正在使用Security (4.0.4)。
当前端点的安全配置(在Java中)允许调用/some/endpoint,但不允许调用/some/endpoint/。
我在这里搜索了文档,但是我没有看到任何类似于忽略尾随的空白空间的开关。例如,使用Spring,我可以执行以下操作:
@Configuration
public class ServletConfig extends WebMvcConfigurerAdapter {
@Override
public void configurePathMatch(final PathMatchConfigurer configurer) {
configurer.setUseTrailingSlashMatch(false);
}
}当然,上面的代码改变了与我想要的相反的行为,但它只是演示了我想使用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();
}我知道我可以使用regex匹配器,这是我想要避免的,主要是因为我想避免对每个端点使用一个额外的规则来批准同一个端点。我必须对每个端点都这样做,这很容易出错。我还知道我可以使用ant并设置到/foo/**的路径。这方面的问题是当我想要控制不同范围的子资源时。
因此,问题是:如何让Security在全球范围内忽略尾斜杠?
提前感谢
发布于 2017-01-06 12:17:25
万一有人有同样的问题,有一个解决办法。它叫做MvcRequestMatcher,你可以在春季文献里读到关于它的所有内容
以下是主要部分:
问题是我们的安全规则只是保护/admin。我们可以为Spring的所有排列添加额外的规则,但这将非常冗长和繁琐。 相反,我们可以利用Security的MvcRequestMatcher。通过使用Spring在URL上匹配,下面的配置将保护Spring将匹配的相同的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();
}https://stackoverflow.com/questions/38207969
复制相似问题