春季安全性5.2:authorizeRequests()中的allowAll()不适用于POST

时间:2020-01-03 15:06:09

标签: spring-security

我有RestController

@RestController
public class HelloController {

    @GetMapping("/no-restriction/action")
    public String action() {
        return "hello";
    }

    @PostMapping("/no-restriction/action")
    public String action(@RequestBody String message) {
        return String.format("You posted '%s'.", message);
    }
}

和配置

@Bean
public OpaqueTokenIntrospector opaqueTokenIntrospector() {
    return token -> null;// TODO
}

@EnableWebSecurity
protected static class OAuth2ResourceServerSecurityConfiguration
extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests(authorizeRequests -> 
            authorizeRequests
                .antMatchers("/no-restriction/**").permitAll()
                .anyRequest().authenticated())
            .oauth2ResourceServer(OAuth2ResourceServerConfigurer::opaqueToken);
    }
}

HTTP请求GET /no-restriction/action(不带任何授权标头)返回200 OK和文本hello。但是POST /no-restriction/action与任何请求正文均不起作用,它将返回401 Unauthorized。为什么POST不起作用?

1 个答案:

答案 0 :(得分:1)

您可能会在请求后丢失CSRF令牌。

Spring安全默认情况下启用CSRF保护。

但是您可以通过以下方式禁用它:

 @Override
 protected void configure(HttpSecurity http) throws Exception {
     http.csrf().disable()
          ...;

 @Override
 protected void configure(HttpSecurity http) throws Exception {
     http.csrf(csrf -> csrf.disable())
          ...;