SpringBoot支持跨域 CORS

it2024-11-12  4

自定义CorsFilter Bean

@Configuration public class CorsConfig { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = getCorsConfigurationSource(); return new CorsFilter(source); } public UrlBasedCorsConfigurationSource getCorsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return source; } }

如果使用了Spring Security,还需要再security config中也添加跨域支持

@Configuration @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityWebConfig extends WebSecurityConfigurerAdapter { @Autowired private CorsConfig corsConfig; @Override public void configure(HttpSecurity http) throws Exception { ... http.cors().configurationSource(corsConfig.getCorsConfigurationSource()); ... } }
最新回复(0)