最近的开发过程中,使用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中可以采用的跨域配置方式如下:
参考Spring Document
在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
标准filter的顺序