Jeffrey · Chiang

CORS

springboot中的跨域请求

什么是跨域

url地址的格式为:协议 + 域名 ( 子域名 + 主域名 ) + 端口号 + 资源地址

只要协议、子域名、主域名、端口号四任一项不同,就认为是不同域, 不同域之间互相访问资源就称之为跨域.

浏览器的默认安全策略使用同源策略,默认不允许跨域请求.但在客户端明确需要,服务端也明确允许的情况下,跨域访问也是合理且被允许的.

什么是CORS

解决跨域请求的方案主要有ISONP、iframe、window.name、CORS, 其中CORS方式最常用的跨域实现方式.

跨域资源共享(CORS, Cross- origin resource sharing)是一种机制,使用额外的HTTP头来告知浏览器让运行在一个origin(domain)上的Web应用被准许访问来自不同源服务器上的指定的资源.

原理:服务器端设置允许跨域的请求头,标识允许哪些域名,以何种方法请求当前域名下的资源.

Spring Boot 中的CORS使用

具体方法个别启用

@RestController
public class UserController {
  @CrossOrigin(value="http://localhost:8080")
  @GetMapping("/users")
  public String selectUsers(){
    return "success"
  }
}

全局启用

创建配置类:

package com.example.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class ProviderMvcConfig implements WebMvcConfigurer {
  @override
  public void addCrosMappings(CorsRegistry registry){
    registry.addMapping("/**") // 所有接口都支持跨域
      .allowedOrigins("http://localhost:8088") // 允许哪些域可访问
      .allowedMethods("*") // 允许所有方法
      .allowedHeaders("*") // 允许所有请求头,包括自定义
  }
}

ProviderMvcConfig实现了WebMvcConfigurer并重写了addCorsMappings