跨域是指从一个域名去请求另外一个域名的资源,即跨域名请求。由于浏览器的同源策略,这种跨域请求可能会受到限制。同源策略是浏览器为了保护用户信息的安全而实施的安全限制,它限制了不同源的客户端脚本在没有明确授权的情况下对对方资源的读写操作。如果出现跨域问题,会发送预检请求,提前检查。
总的来说就是浏览器为了用户的安全,仅允许向同域名、同端口的服务器发送请求。
1. 网关支持Nginx
# 跨域配置
location ^~ /api/ {
proxy_pass http://127.0.0.1:8080/api/;
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers '*';
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
}
2. 修改后端服务
同源安全策略 默认阻止“跨域”获取资源。但是 CORS 给了web服务器这样的权限,即服务器可以选择,允许跨域请求访问到它们的资源。
- Access-Control-Allow-Origin 指示请求的资源能共享给哪些域。
- Access-Control-Allow-Credentials 指示当请求的凭证标记为 true 时,是否响应该请求。
- Access-Control-Allow-Headers 用在对预请求的响应中,指示实际的请求中可以使用哪些 HTTP 头。
- Access-Control-Allow-Methods 指定对预请求的响应中,哪些 HTTP 方法允许访问请求的资源。
- Access-Control-Expose-Headers 指示哪些 HTTP 头的名称能在响应中列出。
- Access-Control-Max-Age 指示预请求的结果能被缓存多久。
- Access-Control-Request-Headers 用于发起一个预请求,告知服务器正式请求会使用那些 HTTP 头。
- Access-Control-Request-Method 用于发起一个预请求,告知服务器正式请求会使用哪一种 HTTP 请求方法。
- Origin 指示获取资源的请求是从什么域发起的。
方式一:配置 @CrossOrigin 注解
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = {"172.268.159.101","ip"},allowCredentials = "true",methods = { RequestMethod.GET,RequestMethod.POST,RequestMethod.OPTIONS})
public class UserController {
}
方式二:添加 web 全局请求拦截器
@Configuration
public class WebMvcConfg implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
//设置允许跨域的路径
registry.addMapping("/**")
//设置允许跨域请求的域名
//当**Credentials为true时,**Origin不能为星号,需为具体的ip地址【如果接口不带cookie,ip无需设成具体ip】
.allowedOrigins("http://localhost:9527", "http://127.0.0.1:9527", "http://127.0.0.1:8082", "http://127.0.0.1:8083")
//是否允许证书 不再默认开启
.allowCredentials(true)
//设置允许的方法
.allowedMethods("*")
//跨域允许时间
.maxAge(3600);
}
}
方式三:返回新的CorsFilter
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setMaxAge(3600L);
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}