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()
}
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()
}
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")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With