Spring Cloud 项目配置跨域

一、前言

对于微服务项目,无需给每个微服务都配置跨域,只需要给网关(Gateway)微服务配置跨域即可。

很多网友给出了多种方案,这里不再赘述。仅在此记录,暂时我遇到的问题。

我通过修改yml配置的形式并不能实现跨域效果。

spring:
  cloud:
    gateway:
      #default-filters:
        #- DedupeResponseHeader=Access-Control-Allow-Origin
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOriginPatterns: "*"     #注意这个设置只对spring boot 2.4+有效,低版本使用  allowedOrigins: "*" 属性
            allowed-methods: "*"
            allowed-headers: "*"
            allow-credentials: true
            exposedHeaders: "Content-Disposition,Content-Type,Cache-Control"

通过断点调试发现,配置的属性没有赋值成功。不知道什么原因。

二、我的做法

1、新建CorsFilter类

import org.springframework.http.HttpMethod;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author gmd
 * @Description 全局跨域配置拦截器
 * @Date 2022-04-28 10:02:29
 */
public class CorsFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        /*// 允许跨域的IP
        String[] allowDomain = {"http://106.205.185.32:1017", "http://127.0.0.1:1017", "http://localhost:1017"};
        Set<String> allowOrigin = new HashSet<>(Arrays.asList(allowDomain));

        // 只有请求的IP在允许跨域的IP里面,才会设置允许请求跨域
        String origin = request.getHeader("Origin");
        if (allowOrigin.contains(origin)) {
            response.setHeader("Access-Control-Allow-Origin", "*");
        }*/

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Origin, X-Requested-With, Accept, Connection, User-Agent, Cookie, token");
        response.setHeader("Access-Control-Max-Age", "3600");

        // 过滤浏览器跨域时发送的预检请求,即如果是预检请求,直接返回200即可
        if (HttpMethod.OPTIONS.name().equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        } else {
            filterChain.doFilter(request, response);
        }
    }

}

 2、将CorsFilter类注入GatewayConfiguration

/**
 * @Author gmd
 * @Description geteway网关配置类
 * @Date 2022-04-28 10:02:29
 */
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(GatewayConfigProperties.class)
public class GatewayConfiguration {

    /**
    * 其他bean
    */


    /**
     * 跨域拦截过滤器配置
     */
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilterRegister() {
        FilterRegistrationBean<CorsFilter> registration = new FilterRegistrationBean<>();
        // 注册拦截器
        registration.setFilter(new CorsFilter());
        // 拦截的URL
        registration.addUrlPatterns("/**");
        registration.setName("corsFilter");
        // 设置该拦截器执行的顺序
        registration.setOrder(0);
        return registration;
    }

}

这样跨域问题就解决了。注意这里已经没有走GlobalCorsProperties类了。

跨域时会产生预检请求(Pre-Flight Request),这样就会对你的服务器产生额外的网络请求。如果可以通过部署手段解决跨域,则可以关闭跨域支持,方法是把以上配置信息清理掉。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在 Spring Cloud Gateway 中配置跨域,可以使用 Spring WebFlux 提供的 CorsConfigurationSource 类。具体步骤如下: 1. 创建一个 CorsConfiguration 对象,配置跨域的属性,比如允许的域名、允许的请求方法等。 ``` CorsConfiguration corsConfig = new CorsConfiguration(); corsConfig.addAllowedOrigin("*"); corsConfig.addAllowedMethod("*"); corsConfig.addAllowedHeader("*"); ``` 2. 创建一个 CorsConfigurationSource 对象,将 CorsConfiguration 对象传入其中。 ``` UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", corsConfig); ``` 3. 在 Spring Cloud Gateway 的配置类中将 CorsConfigurationSource 对象添加到路由过滤器中。 ``` @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { return builder.routes() .route(r -> r.path("/api/**") .filters(f -> f.cors(corsConfigSource)) // 添加跨域过滤器 .uri("lb://service")) .build(); } @Bean public CorsConfigurationSource corsConfigSource() { CorsConfiguration corsConfig = new CorsConfiguration(); corsConfig.addAllowedOrigin("*"); corsConfig.addAllowedMethod("*"); corsConfig.addAllowedHeader("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", corsConfig); return source; } ``` 这样就可以在 Spring Cloud Gateway 中配置跨域了。需要注意的是,由于 Spring Cloud Gateway 是基于 Spring WebFlux 开发的,因此跨域配置方式与传统的 Spring MVC 不同。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值