Johannes Flügel
Johannes Flügel

Reputation: 3262

Spring security 5.2: permitAll() in authorizeRequests() does not work for POST

I have got the 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);
    }
}

and the configuration

@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);
    }
}

The HTTP request GET /no-restriction/action (without any authorization header) returns 200 OK and the text hello. But POST /no-restriction/action with any request body does not work, it will return 401 Unauthorized. Why does the POST not work?

Upvotes: 1

Views: 725

Answers (1)

Dirk Deyne
Dirk Deyne

Reputation: 6936

You probably missing a CSRF-token in your post-request.

CSRF protection is enabled by default by Spring security.

But you can disable this by:

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

or

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

Upvotes: 5

Related Questions