Handling CORS in SpringBoot: Configuration and Custom Filter Solutions
This article explains what CORS is, shows the typical browser error, and provides step‑by‑step SpringBoot configuration and custom filter techniques—including priority settings—to reliably enable cross‑origin requests in Java backend applications.
CORS (Cross-Origin Resource Sharing) is a W3C standard that allows browsers to send Ajax requests to cross‑origin servers, removing the same‑origin restriction.
In a front‑back separation architecture, browsers often show the error “No 'Access-Control-Allow-Origin' header is present on the requested resource.” The article demonstrates how to enable CORS in a SpringBoot project.
SpringBoot CORS configuration
Adding a single configuration class that registers a CorsFilter with permissive settings (allow credentials, any origin, any header, any method) resolves most backend CORS issues.
/**
* Spring Boot 2.0 CORS solution
* @Author javadaily
*/
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
final CorsConfiguration corsConfiguration = new CorsConfiguration();
/* Whether to allow credentials */
corsConfiguration.setAllowCredentials(true);
/* Allowed origins */
corsConfiguration.addAllowedOrigin("*");
/* Allowed headers */
corsConfiguration.addAllowedHeader("*");
/* Allowed methods */
corsConfiguration.addAllowedMethod("*");
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}The filter is injected as a bean, and the asterisks can be replaced with specific values as needed.
When a custom filter writes directly to the response (e.g., response.getWriter().print()), it may bypass the CORS filter, causing the error to reappear because custom filters have higher priority than the WebMvcConfigurer filter.
Solution for special cases
1. Create a custom CustomerCorsFilter that extends CorsFilter and defines its own configuration source.
public class CustomerCorsFilter extends CorsFilter {
public CustomerCorsFilter() {
super(configurationSource());
}
private static UrlBasedCorsConfigurationSource configurationSource() {
// CORS authorization
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
config.addExposedHeader(HttpHeaders.SET_COOKIE);
config.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
}2. Register the filter with a higher precedence using FilterRegistrationBean and setOrder(-1) so that it runs before other custom filters.
@Configuration
public class FilterConfig {
@Bean
public Filter authFilter() {
return new AuthFilter();
}
/**
* WARNING: CORS filter, must be after AuthFilter
*/
@Bean
public FilterRegistrationBean corsFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new CustomerCorsFilter());
List<String> urlList = new ArrayList<>();
urlList.add("/*");
registration.setUrlPatterns(urlList);
registration.setName("CorsFilter");
registration.setOrder(-1); // smaller order = higher priority
return registration;
}
@Bean
public FilterRegistrationBean authFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(authFilter());
List<String> urlList = new ArrayList<>();
urlList.add("/*");
registration.setUrlPatterns(urlList);
registration.setName("authFilter");
registration.setOrder(1);
return registration;
}
}By setting the order, the CORS filter executes before the custom authentication filter, ensuring that CORS headers are added to the response.
Note: a smaller order value means higher priority.
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.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
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.
