Published on

Getting CORS to Work for A Given Path on Spring Boot


Today I had to wire a front-end app to a backend Spring Boot API. The API is public and does not need authentication but I kept running into preflight errors related to CORS. These errors are due to how browsers handle CORS and require this to be handled on the server (i.e. nothing can be done client-side). After a bit of fiddling, I eventually ended up with the following solution.

Assume I have an API exposed under: https://localhost:8080/my/api and the website is exposed under http://localhost:3000 and http://localhost:3001 (I added this to illustrate how to add CORS for multiple calling URLs). I first started by adding to my as follows:

  • Spring will treat comma-separated values as an array

I created a bean to hold these properties:

import org.springframework.context.annotation.Configuration

@ConfigurationProperties(prefix = "security.cors")
class SecurityCorsProperties {

    lateinit var uiBaseUrlPatterns: Array<String>

Finally, I configured Spring Security to use this as follows:

class WebSecurityConfig {

class CorsConfiguration : WebMvcConfigurer {

    lateinit var securityCorsConfiguration: SecurityCorsProperties

    override fun addCorsMappings(registry: CorsRegistry) {
            .allowedMethods("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")