Java
Java

Reputation: 363

Can't use @RequestBody with PostMapping only with GetMapping

If I use @GetMapping and @RequestBody everything works fine, but if I change only @GetMapping to @PostMapping I get this error in postman:

"status": 403,
"error": "Forbidden",
"message": "Forbidden",
    @GetMapping(value =  "/insert") //works
       public Long insert(@RequestBody T entity){
          ...
       }
    }

    @PostMapping(value =  "/insert") //does not work
       public Long insert(@RequestBody T entity){
          ...
       }
    }

Upvotes: 1

Views: 1151

Answers (1)

n0rdy
n0rdy

Reputation: 56

@GetMapping and @PostMapping are Spring MVC annotations, but 403 - is a security issue related HTTP code. So the problem is definitely in Spring Security configurations.

There is high chances that the purpose of the issue is CSRF protection that is enabled by default in Spring Security.

To give it a try, please to disable CSRF protection in your config in a following way:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

Afterwards, POST requests should be allowed within the application.

Upvotes: 3

Related Questions