1.跨域就指着协议,域名,端口不一致,出于安全考虑,跨域的资源之间是无法交互的。简单说就是协议不通,域名不通,端口不同都会产生跨域问题
Access-Control-Allow-Origin是HTML5中定义的一种解决资源跨域的策略。他是通过服务器端返回带有Access-Control-Allow-Origin标识的Response header,用来解决资源的跨域权限问题。
2.单个应用解决跨域问题
@Configuration public class CorsConfig extends WebMvcConfigurerAdapter { static final String[] ORIGINS = new String[]{"GET", "POST", "PUT", "DELETE"}; @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") //可访问ip,ip最好从配置文件中获取, .allowedOrigins("*") .allowedMethods(ORIGINS) //.allowedHeaders("*") .exposedHeaders("access-control-allow-headers", "access-control-allow-methods", "access-control-allow-origin", "access-control-max-age", "X-Frame-Options", "token", "channel") .allowCredentials(true).maxAge(3600); } }
或者可以使用Filter
@Component public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest reqs = (HttpServletRequest) req; // response.setHeader("Access-Control-Allow-Origin",reqs.getHeader("Origin")); response.setHeader("Access-Control-Allow-Origin","*"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); chain.doFilter(req, res); } @Override public void init(FilterConfig filterConfig) {} @Override public void destroy() {} }
3.如果是在微服务环境中,网关层会首先做跨域问题解决。
@Bean public CorsFilter corsFilter() { final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); final CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); // 允许cookies跨域 config.addAllowedOrigin("*");// 允许向该服务器提交请求的URI,*表示全部允许。。这里尽量限制来源域,比如http://xxxx:8080 ,以降低安全风险。。 config.addAllowedHeader("*");// 允许访问的头信息,*表示全部 config.setMaxAge(18000L);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了 config.addAllowedMethod("*");// 允许提交请求的方法,*表示全部允许,也可以单独设置GET、PUT等 config.addAllowedMethod("HEAD"); config.addAllowedMethod("GET");// 允许Get的请求方法 config.addAllowedMethod("PUT"); config.addAllowedMethod("POST"); config.addAllowedMethod("DELETE"); config.addAllowedMethod("PATCH"); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); }
4.如果在微服务环境中,网关层做了跨域问题解决,单个服务也做了跨域问题处理,这时就会出现*多次配置问题
这时候需要在Zuul配置忽略头部信息
zuul: #需要忽略的头部信息,不在传播到其他服务 sensitive-headers: Access-Control-Allow-Origin ignored-headers: Access-Control-Allow-Origin,H-APP-Id,Token,APPToken