How to Fix CORS Issues After Upgrading to Spring Boot 2.5.x
Upgrading a Spring Boot application from 2.1.8 to 2.5.6 can break existing CORS configurations, but adding a WebMvcConfigurer bean with allowedOriginPatterns resolves the new cross‑origin restrictions, as demonstrated with concrete code examples.
Cross‑origin resource sharing (CORS) occurs when a request’s protocol, domain, or port differs from the page’s URL, and browsers block such requests due to the same‑origin policy, a fundamental security mechanism.
Why CORS Happens
The same‑origin policy prevents JavaScript from one origin from interacting with resources from another, protecting browsers from malicious cross‑site interactions.
Old Solution for Spring Boot 2.1.8
In Spring Boot 2.1.8 the common fix is to create a @Configuration class that registers a CorsFilter bean, allowing all origins, methods, and headers:
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.setAllowCredentials(true);
config.addAllowedMethod("*");
config.addAllowedHeader("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}New Issue in Spring Boot 2.5.6
After upgrading to 2.5.6 the above filter no longer resolves CORS problems because the framework’s handling of CORS has changed.
Official Solution for Spring Boot 2.5.x
The documentation recommends adding a WebMvcConfigurer bean that configures CORS mappings with allowedOriginPatterns("*") and enables credentials:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowCredentials(true).allowedOriginPatterns("*");
}
};
}Adding this bean under the application’s main class eliminates the CORS errors introduced by the upgrade.
Once the new configuration is in place, cross‑origin requests succeed, confirming the fix.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Coder Trainee
Experienced in Java and Python, we share and learn together. For submissions or collaborations, DM us.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
