最近的开发过程中,使用spring集成了spring-cloud-zuul,但是由于服务部署在线上,本地调试存在跨域问题,导致报错:403 forbidden Invalid CORS request 解决问题的过程中总结了spring的跨域处理策略(精读spring和spring boot的文档都能找到解决方案)
项目情况:spring +spring boot+spring-cloud-zuul+spring security
问题
之前使用下方介绍的配置2进行了跨域配置,但是采用zuul的时候,报错403,测试之后发现问题在于filter的执行顺序,给出了3的解决方案;3正常之后,发现本地调试未登录情况下,前端不能捕获401错误
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:8088' is therefore not allowed access.
The response had HTTP status code 401.
猜测是spring security的filter在全局配置的跨域filter之前,所以有了4的配置。
方案
spring中可以采用的跨域配置方式如下:
RequestMapping
在一般性的配置中,在controller前添加@CrossOrigin即可使用spring的默认配置,允许跨域
该注解也可以配置一些设定,适合针对个别的controller
webconfig的方式配置全局跨域
@Configuration
public class JxWebMvcConfiguration extends WebMvcConfigurerAdapter {
/**
* Cross Origin Resource Support(CORS) for the Spring MVC.
* automatically.
* https://my.oschina.net/wangnian/blog/689020
* http://spring.io/guides/gs/rest-service-cors/
*/
/* @Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("*")
.allowedOrigins("*").exposedHeaders("x-total-count","x-auth-token")
.allowedMethods("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "TRACE");
}*/
}
这种方式的缺陷是,filter的顺序是固定的,在引入第三方组件的时候可能会因为filter滞后,导致出错
定制Filter
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
方案3缺陷
在3中,我使用zuul的时候,的确解决了跨域问题,但是spring security的filter还是在其前边,引起登录的时候不能正常捕获401错误
@Bean
public Filter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
config.addExposedHeader("x-auth-token");
config.addExposedHeader("x-total-count");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.addFilterBefore(corsFilter(), ChannelProcessingFilter.class);
}
参考
Spring Boot Data Rest + CORS not being enabled properly for OPTIONS/DELETE