电光石火-穿越时空电光石火-穿越时空


springcloud zuul的跨域问题

正常情况下,跨域是这样的: 
1. 微服务配置跨域+zuul不配置=有跨域问题 
2. 微服务配置+zuul配置=有跨域问题 
3. 微服务不配置+zuul不配置=有跨域问题 
4. 微服务不配置+zuul配置=ok

然而云环境中每个服务自己有跨域解决方案,而网关需要做最外层的跨域解决方案.如果服务已有跨域配置网关也有,会出现*多次配置问题。

Access-Control-Allow-Origin:"*,*"
也就是multiple Access-Control-Allow-Origin

!!!所以我们就要,微服务配置+zuul配置=解决跨域问题


zuul的跨域忽略配置
使用ZUUL配置忽略头部信息

zuul:
#需要忽略的头部信息,不在传播到其他服务
  sensitive-headers: Access-Control-Allow-Origin
  ignored-headers: Access-Control-Allow-Origin,H-APP-Id,Token,APPToken

微服务应用的跨域配置

@Component  
public class CorsFilter implements Filter {  
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {  
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;  
       /* String curOrigin = request.getHeader("Origin");
        System.out.println("###跨域过滤器->当前访问来源->"+curOrigin+"###");   */
        response.setHeader("Access-Control-Allow-Origin", "*");  
        response.setHeader("Access-Control-Allow-Methods", "*");  
        response.setHeader("Access-Control-Max-Age", "3600");  
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); 
        chain.doFilter(req, res);  
    }  
    @Override
    public void init(FilterConfig filterConfig) {}  

    @Override
    public void destroy() {}  
}  

zuul路由的跨域配置

@Component
@Configuration
public class GateWayCorsConfig
{
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
//        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }
}
本博客所有文章如无特别注明均为原创。作者:似水的流年
版权所有:《电光石火-穿越时空》 => springcloud zuul的跨域问题
本文地址:http://ilkhome.cn/index.php/archives/395/
欢迎转载!复制或转载请以超链接形式注明,文章为 似水的流年 原创,并注明原文地址 springcloud zuul的跨域问题,谢谢。

评论