Streamlining Cross-Origin Resource Sharing in Spring Boot
The Problem
When developing the brisavillca/Backend project, we encountered recurring browser-side blocks during API requests. Despite a solid backend foundation, our frontend client struggled to communicate with our services due to strict Cross-Origin Resource Sharing (CORS) policies. Every time the frontend attempted a request, the browser would reject the connection, treating the backend as an untrusted third party.
The Approach
To resolve this, we moved away from default security behaviors and implemented a centralized CORS configuration within our Spring application. The goal was to explicitly define which origins, headers, and methods are allowed, moving from a "block-all" posture to a "securely-enabled" one.
Configuring the CORS Registry
In Spring, the cleanest way to handle this is by implementing the WebMvcConfigurer interface. This allows us to define global rules that apply to all controllers in the project:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("https://example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true);
}
}
By centralizing this configuration, we ensure that every controller adheres to the same security standards, making the API predictable and accessible to our authenticated frontends.
Why This Matters
Think of CORS as the bouncer at a club entrance. By default, the bouncer doesn't know who is on the list, so they turn everyone away. By configuring the WebMvcConfigurer, we are essentially giving the bouncer a guest list. Now, instead of blocking every request, they only check the request's origin against our allowed list, letting authorized traffic pass through smoothly.
Key Insights
- Be Specific: Never use
allowedOrigins("*")in production; always list the specific domains that need access. - Centralize: Configuring CORS at the global level prevents the common "spaghetti code" approach of adding
@CrossOriginannotations to every single controller. - Authentication Matters: If your API uses cookies or session tokens,
allowCredentials(true)is mandatory, but it requires that yourallowedOriginsbe explicit rather than a wildcard.
Generated with Gitvlg.com