Spring Security(Java Config):使用不同HTTP方法的相同URL的antmatcher

时间:2017-05-05 17:26:19

标签: spring-security

我试图限制对一个角色的URL的GET访问权限,以及对另一个角色的同一URL的POST访问权限,如下所示。

-v true

当我使用我的readuser帐户尝试GET(或POST)时,我收到拒绝访问错误;但是当我尝试使用管理员帐户时,它可以同时执行这两项操作。

但是,当我删除行@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("password").roles("USER").and() .withUser("readuser").password("password").roles("USER", "READ").and() .withUser("admin").password("password").roles("USER", "READ", "WRITE"); } protected void configure(HttpSecurity http) throws Exception { http .formLogin().permitAll().and() .logout().permitAll().and() .authorizeRequests() .antMatchers(HttpMethod.GET, "/api/foo").hasRole("READ") .antMatchers(HttpMethod.POST, "/api/foo").hasRole("WRITE") .anyRequest().authenticated() .and().csrf().disable() .httpBasic(); 时,我的readuser帐户可以使用GET请求正确命中/ api / foo。

如何让Spring Security允​​许这两种限制?

更新 - 包括相关的弹簧安全调试日志信息

以下是尝试使用readuser时的相关日志:

.antMatchers(HttpMethod.POST, "/api/foo").hasRole("WRITE")

1 个答案:

答案 0 :(得分:1)

您使用的是错误的HttpMethod类。

javax.ws.rs.HttpMethod#GET会返回String,因此您在Spring Security配置中使用antMatchers(String... antPatterns)而不是antMatchers(HttpMethod method, String... antPatterns)

使用该配置,Spring Security会检查URL模式GET/api/foo(两者都适用于所有HTTP方法),请参阅日志:

2017-05-08 11:31:27.817 DEBUG 5812 --- [p1731685294-106] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/api/foo'; against 'GET' 
2017-05-08 11:31:27.817 DEBUG 5812 --- [p1731685294-106] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/api/foo'; against '/api/foo'

您必须使用org.springframework.http.HttpMethod#GET,它会返回HttpMethod个对象。

相关问题