Spring boot 跨域设置,有2种方式(亲测有效):
方式一:
@Configuration public class CorsConfig { // <p>Description:配置允许跨域访问</p> private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); //要设置为False,否则web漏洞扫描会提示CORS origin validation failure corsConfiguration.setAllowCredentials(false); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); return corsConfiguration; } //<p>Description:跨域过滤器</p> @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); return new CorsFilter(source); } }
方式二:
@Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Bean public V8Interceptor vxInterceptor(){ return new V8Interceptor(); } @Override //20210825 : 重写父类提供的跨域请求处理的接口 public void addCorsMappings(CorsRegistry registry) { //添加映射路径 registry.addMapping("/**") .allowedOrigins("*") //是否发送Cookie信息, allowedOrigins设置*,则allowCredentials不能设置true .allowCredentials(false) //放行哪些原始域(请求方式) .allowedMethods("GET","POST", "PUT", "DELETE") //放行哪些原始域(头部信息) .allowedHeaders("*") //暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息) .exposedHeaders("username", "usertoken","wxapitoken","lan_ip","net_ip"); } }
这2种方式都是可行的,但是要注意其中的 allowCredentials 都是设置为false,也就是不传入cookie信息,如果设置为true,当进行web弱点扫描时,会提示:
CORS origin validation failure
所以建议设置为False