0
votes

I have Spring Boot REST API and React based CMS.

When I send GET ajax requests to the API, they work fine. But when I send POST requests I am stopped by CORS error:

Access to XMLHttpRequest at 'http://localhost:8080/item/add' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I am using WebSecurityConfigurerAdapter to configure security.

BasicWebSecurityConfigurerAdapter.kt

override fun configure(http: HttpSecurity?) {
    http?.csrf()?.disable()
    http?.cors()
    http?.authorizeRequests()
            ?.anyRequest()?.authenticated()
            ?.and()
            ?.httpBasic()
}

@Bean
fun corsConfigurationSource(): CorsConfigurationSource {
    val configuration = CorsConfiguration()
    configuration.allowedOrigins = mutableListOf("http://localhost:3000")
    configuration.allowedMethods = mutableListOf("GET", "POST")

    val source = UrlBasedCorsConfigurationSource()
    source.registerCorsConfiguration("/**", configuration)

    return source
}

I have also tried using annotations instead on my RestControllers, but I had the same issue, GET requests working and POST requests not working. I am still fairly new to Spring Boot, so I am sure there is something I am missing.

1
Annotations like @CrossOrigin on top of my controllers methods work perfect for me. - Rinat Suleimanov
As I wrote in the question, I get the same result using them. I tried annotations first, before I tried to use the WebSecurityConfigurerAdapter. - Tomáš Chylý
Just in case, what spring boot version do you use? I'm using 2.1.4.RELEASE. Could you also provide more code? Will try to reproduce it locally. - Rinat Suleimanov
Spring Boot is 2.1.6.RELEASE, I will update the question with more code. - Tomáš Chylý
Thank you :) When I was about to update the question, I re-read the code and was able to find bug, it was completely somewhere else. - Tomáš Chylý

1 Answers

2
votes

Ok, when I was re-reading the code, I found the reason why this does not work. There was a bug in the CMS not Spring Boot API. I was using wrong API endpoint. So you do not get 404 error, but CORS one.

But, for some reason the CORS does not work using the WebSecurityConfigurerAdapter. Instead I have returned back to using annotations, @CrossOrigin, on controllers.