- Published on
Getting CORS to Work for A Given Path on Spring Boot
- Authors
- Name
- Yair Mark
- @yairmark
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 application.properties
as follows:
## CORS
security.cors.uiBaseUrlPatterns=http://localhost:3000,http://localhost:3001
- Spring will treat comma-separated values as an array
I created a bean to hold these properties:
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.Configuration
@Configuration
@ConfigurationProperties(prefix = "security.cors")
class SecurityCorsProperties {
lateinit var uiBaseUrlPatterns: Array<String>
}
Finally, I configured Spring Security to use this as follows:
@Configuration
@EnableWebSecurity
class WebSecurityConfig {
//...
@Configuration
class CorsConfiguration : WebMvcConfigurer {
@Autowired
lateinit var securityCorsConfiguration: SecurityCorsProperties
override fun addCorsMappings(registry: CorsRegistry) {
registry.addMapping("/my/api")
.allowedMethods("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")
.allowCredentials(true)
.allowedOriginPatterns(*securityCorsConfiguration.uiBaseUrlPatterns)
}
}
}