Tomáš Chylý
Tomáš Chylý

Reputation: 342

Spring Boot Security CORS with POST request

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.

Upvotes: 1

Views: 630

Answers (1)

Tomáš Chylý
Tomáš Chylý

Reputation: 342

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.

Upvotes: 2

Related Questions