CORS 跨域请求

CORS 原理

CORS (跨域资源共享) 浏览器同源策略的解决方案,通过 HTTP 头信息协商跨域请求的合法性

  • 预检请求(Prefilght) : 对于非简单的请求(PUT, DETELE) ,浏览器先发送 OPTIONS 请求,服务器需返回允许的跨域头信息
  • 关键响应头:
  • Access-Control-Allow-Origin : 允许的来源(\* 即是允许所有的请求数据)
  • Access-Control-Allow-Methods : 允许的 HTTP 方法
  • Access-Control-Allow-Headers : 允许的请求头

WebMvcConfigurer 实现

开源代码地址

@Configuration
@Slf4j
public class CORSConf {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                log.info("初始化 CORSConfiguration 配置");
                registry.addMapping("/**")  // 允许的请求路径是 * 即是全部路径允许访问
                        .allowedHeaders("*")  // 允许所有的请求头进行跨域操作
                        .allowedMethods("*")  // 允许所有的请求方法进行跨域请求
                        .allowedOrigins("*");  // 允许所有的请求来源进行跨域请求
            }
        };
    }
}

使用@CrossOrigin实现

实现局部的配置跨域请求的方法实现,在指定的方法或者对应的实现Controller实现类上面进行注解操作

// 实现允许 GET, POST 方法进行跨域请求
@RestController
@CrossOrigin(origins = "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class DemoController {
    // 接口方法
}

配置spring-clould的gateway实现

使用 API 网关即 spring-gateway 实现跨域请求的定义

【优点】统一配置对应的跨域请求Config ,方便管理

【缺点】需要导入对应的spring-gateway的依赖导致项目的依赖增多

spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          "[/**]":
            allowedOrigins: "*"
            allowedMethods: "*"
            allowedHeaders: "*"

配置 Nginx 实现

使用前端的网关配置 Nginx 实现跨域请求转发操作

【优点】 统一管理,不依赖后端技术栈

【缺点】 需要维护 Nginx 配置,每次都要上线修改 Nginx 的 Conf 文件

location / {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
    if ($request_method = OPTIONS) {
        return 204;
    }
}