1. 跨域问题的由来
由于浏览器的同源策略,不同源的客户端在没有明确授权的情况下,无法
跨域访问另一个域的资源。
同源策略:如果两个页面的协议,端口和主机都相同,则两个页面具有相同的源。下面是相对http://192.168.0.100/index.html为例同源检测示例:
url | 结果 |
---|---|
http://192.168.0.100/page | 可以,只有URL不用 |
http://192.168.0.100:8081/page | 不可以,端口不同 |
http://192.168.0.101/page | 不可以,主机域名不同 |
https://192.168.0.100/page | 不可以,协议不同 |
2. 跨域请求解决方案:Cross Origin Resource Share (CORS)
CORS通过增加一系列请求头和响应头的方式来规范解决跨域请求数据安全传输。
请求头
请求头 | 备注 |
---|---|
Origin | 跨域请求要访问的域名 |
Access-Control-Request-Method | 跨域请求的http请求方法 |
Access-Control-Request-Headers | 告知服务器携带请求头信息 |
with-credentials | 跨域请求携带cookie |
响应头
响应头 | 备注 |
---|---|
Access-Control-Allow-Origin | 服务器验证后的跨域请求域名 |
Access-Control-Expose-Headers | 允许返回给跨域请求的响应头列表,列表的响应头内容才能被浏览器访问 |
Access-Control-Max-Age | 预先检查请求返回结果缓存的时间,在缓存有效期内,浏览器会使用缓存的预先检查结果判断是否发送跨域请求。 |
Access-Control-Allow-Methods | 告知浏览器跨域请求时支持的请求方法 |
3. Spring Boot配置跨域请求处理
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.setAllowCredentials(true);
config.addAllowedMethod("*");
config.addAllowedHeader("*");
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
return new CorsFilter(configSource);
}
}
参考:
https://segmentfault.com/a/1190000017867312?utm_source=tag-newest
https://developer.mozilla.org/zh-CN/docs/Web/Security/Same-origin_policy