Spring Boot中Cors Filter失效问题求助
Hey there, let’s figure out why your CORS filter isn’t working as expected. I’ve run into this exact scenario multiple times, so let’s break down the common pitfalls and fixes step by step.
First, Spot the Critical Conflict in Your Config
Looking at your code, you’ve set config.setAllowCredentials(true) and config.addAllowedOrigin("*") together — this is a browser-enforced restriction. Browsers block requests where credentials are allowed but the origin is a wildcard (*). That’s probably the biggest reason your filter isn’t behaving.
Fixes to Get Your CORS Filter Working
1. Resolve the Origin-Credentials Conflict
If you need to allow credentials (like cookies or HTTP auth), replace the wildcard origin with specific domain patterns or exact domains. For development, you can use addAllowedOriginPattern("*") (note the difference from addAllowedOrigin — this supports pattern matching and works with credentials):
@Bean public FilterRegistrationBean<CorsFilter> corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); // Use origin pattern instead of wildcard for credential support config.addAllowedOriginPattern("*"); // For production, replace with your frontend domain: // config.addAllowedOrigin("https://your-frontend-app.com"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); // Make sure this line is complete! FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source)); // Ensure CORS filter runs before other filters (like auth filters) bean.setOrder(Ordered.HIGHEST_PRECEDENCE); return bean; }
2. Ditch the Custom SimpleCORSFilter (If Unnecessary)
Your code references a custom SimpleCORSFilter, but Spring’s built-in CorsFilter paired with UrlBasedCorsConfigurationSource is designed to handle CORS out of the box. Using a custom filter might override or interfere with Spring’s native handling unless you’ve specifically tailored it for edge cases. Stick with the native implementation unless you have a clear reason to customize.
3. Verify Filter Execution Order
If you have other filters (like JWT auth or security filters) running before your CORS filter, those might reject the request before the CORS headers are added. Setting bean.setOrder(Ordered.HIGHEST_PRECEDENCE) ensures the CORS filter runs first, which is crucial for preflight OPTIONS requests.
4. Check Browser Console for Clues
Open your browser’s dev tools (Network tab) and look at the preflight OPTIONS request response. If you see an error like:
Credentials flag is 'true' but the 'Access-Control-Allow-Origin' header is '*'
That confirms the origin-credentials conflict we talked about earlier.
Alternative: Use WebMvcConfigurer for Simpler CORS Setup
If you’re on Spring Boot 2.2+, you can skip the filter bean entirely and use a configuration class with WebMvcConfigurer:
@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOriginPatterns("*") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(true) .maxAge(3600); } }
This approach is often more straightforward and less error-prone for standard CORS needs.
内容的提问来源于stack exchange,提问作者Pooja Mahapatra

