一、同源策略简介
同源策略[same origin policy]是浏览器的一个安全功能,不同源的客户端脚本在没有明确授权的情况下,不能读写对方资源。 同源策略是浏览器安全的基石。
什么是源
源[origin]就是协议、域名和端口号。例如:http://www.baidu.com:80这个URL。
什么是同源
若地址里面的协议、域名和端口号均相同则属于同源。
是否是同源的判断
例如判断下面的URL
是否与 http://www.a.com/test/index.html 同源
- http://www.a.com/dir/page.html 同源
- http://www.child.a.com/test/index.html 不同源,域名不相同
- https://www.a.com/test/index.html 不同源,协议不相同
- http://www.a.com:8080/test/index.html 不同源,端口号不相同
请求头
- Access-Control-Allow-Methods: 真实请求允许的方法
- Access-Control-Allow-Headers: 服务器允许使用的字段
- Access-Control-Allow-Credentials: 是否允许用户发送、处理 cookie
- Access-Control-Max-Age: 预检请求的有效期,单位为秒。有效期内,不会重复发送预检请求
二、同源策略本地测试
1. 打开浏览器 ,F12调出开发者页面 进入 console,输入以下代码,执行
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://xxx.com/common/listCity");
xhr.send(null);
xhr.onload = function(e) {
var xhr = e.target;
console.log(xhr.responseText);
}
得到结果 出现跨域问题。
三、Spring Boot 配置 CORS
1、使用@CrossOrigin
注解实现
#
如果想要对某一接口配置 CORS
,可以在方法上添加 @CrossOrigin
注解 :
@CrossOrigin(origins = {"http://localhost:9000", "null"})
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String greetings() {
return "{\"project\":\"just a test\"}";
}
#
如果想对一系列接口添加 CORS 配置,可以在类上添加注解,对该类声明所有接口都有效:
@CrossOrigin(origins = {"http://localhost:9000", "null"})
@RestController
@SpringBootApplication
public class SpringBootCorsTestApplication {
}
2.如果想添加全局配置,则需要添加一个配置类 :
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.maxAge(3600)
.allowCredentials(true);
}
}
3.另外,还可以通过添加 Filter 的方式,并手动指定对哪些接口有效。
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true); config.addAllowedOrigin("http://localhost:9000");
config.addAllowedOrigin("null");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config); // CORS 配置对所有接口都有效
FilterRegistrationBean bean = newFilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
4.直接配置文件application.yml文件
#跨域配置和json序列化配置 mvc: cors: enabled: true #是否启用 path : "/**" #哪些URL可以跨域 allowedOrigins: "*" #哪些域名可以请求跨域,逗号隔开 allowedMethods: "*" #哪些方法可以跨域 POST, GET, PUT, DELETE, OPTIONS exposedHeaders: message