0

My Spring Boot application provides several endpoints. Following this article, I'd like to restrict all endpoints by default, so that they require authentication via a JWT token. Only certain paths shall be public. My understanding is that all paths defined in .antMatchers(PUBLIC_RESOURCES).permitAll() will be "public" without any authentication.

This works fine for the GET method but when hitting the same endpoint(s) with a POST then I get a HTTP 403 (Forbidden). I don't understand the reason for this.

This is my current security configuration:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private static final String[] PUBLIC_RESOURCES = {
            "/",
            "/user/login"
    };

    @Override
    protected void configure(final HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .antMatcher("/**").authorizeRequests()
                .antMatchers(PUBLIC_RESOURCES).permitAll()
                .anyRequest().authenticated();
    }
}

And the controller:

@RestController
@RequestMapping(path = "user")
public class LoginController {

    @GetMapping
    public String get() {
        return "Hey, Joe (get)";
    }

    @PostMapping
    public String post() {
        return "Hey, Joe (post)";
    }
}
Robert Strauch
  • 12,055
  • 24
  • 120
  • 192

1 Answers1

1

it's probably because of the CSRF protection that affects all requests that mutate the state of the server (POST, PUT, DELETE etc.).

you can read more about csrf here:

What is CSRF?

How to configure or disable csrf in spring security.

Im guessing you want to disable it (which i dont recommend, because it is a security feature)

How to disable csrf in spring security.

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

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

I highly recommend turning on spring security debug logging, and the logs will tell you exactly why your request is getting denied.

application.properties

logging.level.org.springframework.security=DEBUG
Toerktumlare
  • 12,548
  • 3
  • 35
  • 54
  • Thanks, this clarifies things. A quick test disabling CSRF shows that this is the root cause. I ended up adding `.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())` to the security configuration. – Robert Strauch Jan 28 '21 at 21:52