Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring security antMatchers not being applied on POST requests and only works with GET

I am using Spring security library to secure REST apis in my application, I am trying now to allow access to all URLs (temporarily) but with the below configuration I find that only GET requests are allowed but not the POST requests (where I get 403 forbidden response), I understand that the first antmatcher below should allow both GET & POST but actually the 2 antMatchers couldn't allow POST

Can someone please advise me on what I am missing here?

protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
// first I have tried only this antMatcher
            .antMatchers("/**").permitAll()
// But then it didn't allow POST even when only using the line below
            .antMatchers(HttpMethod.POST, "/**").permitAll()
}
like image 897
Ahmed Elkoussy Avatar asked Jun 28 '18 09:06

Ahmed Elkoussy


3 Answers

After some investigation, it turned out that antMatcher was working as expected & allowing all URLs as intended, but the reason for the forbidden response that I was getting for the POST APIs was that Spring security was waiting for csrf token for these POST requests because CSRF protection is enabled by default in spring security.

So in order to make it work like this, you must provide the csrf token in POST request OR you can temporarily turn CSRF protection off (but you should enable it again before going to production as this is a serious attack)

Example code for that:

protected void configure(HttpSecurity http) throws Exception {
    http
        // disabling csrf here, you should enable it before using in production
        .csrf().disable()
        .authorizeRequests()
       // this matcher is working for all GET/POST/... , any URL matching the reg expression
            .antMatchers("/**").permitAll()
}
like image 175
Ahmed Elkoussy Avatar answered Oct 27 '22 03:10

Ahmed Elkoussy


As stated by the Questioner in your own reply, the 403 forbidden error could be caused by the CSRF protection. But instead of disable this protection, you can except some AntMatchers like this:

http
                (...) // oculted for brevity
                .and()
                .csrf()
                    .ignoringAntMatchers("/api/a", "/api/b")
like image 35
Bruno Morais Avatar answered Oct 27 '22 05:10

Bruno Morais


You need to do something similar this and you should mention role

http
  .httpBasic().and()
  .authorizeRequests()
    .antMatchers(HttpMethod.POST, "/employees").hasRole("ADMIN")
    .antMatchers(HttpMethod.PUT, "/employees/**").hasRole("ADMIN")

Hope it will solve your issue.

like image 32
Bala venkatesh Avatar answered Oct 27 '22 05:10

Bala venkatesh