一、 什么是跨域(同源策略)
同源的定义:如果两个页面的协议,端口(如果有指定)和主机都相同,则两个页面具有相同的源
1,用户在浏览器输入的URL中包含的协议、域名、端口都完全相同。如果有一项不同,浏览器会觉得有安全问题,从而产生跨域问题。,
2,如果使用Postman等开发工具进行交互是不会出现跨域问题,这是浏览器特有的限制。
在后端服务添加CORS策略的配置就可以解决跨域问题。
一,Spring Cloud Gateway 跨域配置
spring:
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]': # 允许跨域的源(网站域名/ip),设置*为全部
allow-credentials: true
allowed-origins: #起源
- "http://xb.abc.com"
- "http://sf.xx.com"
allowed-headers: "*" # 允许跨域请求里的head字段,设置*为全部
allowed-methods: # 允许跨域的method, 默认为GET和OPTIONS,设置*为全部
- OPTIONS
- GET
- POST
- DELETE
- PUT
- PATCH
max-age: 3600
二,Spring boot项目
1,使用@CrossOrigin注解 (局部跨域)
在支持跨域的方法或类上添加@CrossOrigin注解
@CrossOrigin(origins = "*")
2,重写 WebMvcConfigurer(全局跨域)
Spring boot项目更便捷的方式,实现WebMvcConfigurer接口中的addCorsMappings方法。
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
//放行哪些原始域
.allowedOrigins("*")
.allowedHeaders("*")
// 是否发送Cookie
.allowCredentials(true)
.allowedMethods("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH")
.maxAge(3600);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/");
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("doc.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
三,反向代理服务器
使用反向代理服务器可以将前端请求转发到后端服务器,从而绕过跨域限制。以下是反向代理服务器的示例代码:
这里nginx是要和你的前端服务在一台服务器上的,然后你访问的时候通过前端的nginx进行转发的后端服务器才行
NGINX反向代理配置示例
location /api {
proxy_pass http://backend-server;
}
四,Spring解决跨越
添加处理跨域的过滤器(CoreFilter)。
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter(){
CorsConfiguration config=new CorsConfiguration();
//config.addAllowedOrigin("*"); -过时的
//允许哪些域名访问
config.addAllowedOriginPattern("*");
//是否允许前端传递验证信息 cookie
config.setAllowCredentials(true);
//允许所有的方法 POST GET ...
config.addAllowedMethod("*");
//允许哪些请求头
config.addAllowedHeader("*");
//暴露哪些头部信息
config.addExposedHeader("*");
//设置允许哪些接口可以被跨域访问
UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**",config);
return new CorsFilter(source);
}
}