前言
本文写的会有些仓促,因为我也是刚刚 5 分钟之内完成了全局跨域配置、打包、上传、启动、成功访问这几个步骤。所以本文不分析跨域的问题,直接提供三种方式帮你解决 SpringBoo t项目跨域问题。
正文
浏览器为什么要有跨域:浏览器的一个安全功能,不同源的客户端脚本在没有明确授权的情况下,不能读写对方资源。 同源策略是浏览器安全的基石。
跨域产生的原因:协议、域名和端口号只要有一项不匹配就产生跨域,都满足才叫同源。
问题场景:
刚对接一项目,写了一个对接中移 获取 token 的接口,部署后前端老哥给我发来一张图,我的锅,尴不尴尬!!
个人分析:
- 大家都知道 HTTP状态中 4 段的都是客户端问题,403是没有权限访问此站。
- options请求是用于请求服务器对于某些接口等资源的支持情况的,包括各种请求方法、头部的支持情况通过上面截图不难看出资源获取请求是失败的。
- 还有后面一大段英语的意思,断定 100% 跨域问题。
方法一
@CrossOrigin()注解实现
对某一接口配置跨域,在该方法上添加注解,origins 参数 含义是能处理来自http:19.168.1.97:8080中的请求。
@CrossOrigin(origins = {"http://192.168.1.97:8080", maxAge = 3600})
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String greetings() {
return "{\"project\":\"just a test\"}";
}
对一系列接口配置跨域,在启动类添加注解。
@CrossOrigin(origins = {"http://192.168.1.97:8080", maxAge = 3600})
@RestController
@SpringBootApplication
public class SpringBootCorsTestApplication {
}
对当前 controller 配置跨域,注解可用在类上。
@CrossOrigin(origins = "http://192.168.1.97:8080", maxAge = 3600)
@RequestMapping("rest_index")
@RestController
public class IndexController{
}
方法二
全局设置跨域
该方法推荐写在 网关中,一劳永逸。
- exposedHeaders属性:可以不写。配置响应的头信息, 在其中可以设置其他的头信息,不进行配置时, 默认可以获取到Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma字段。
- allowCredentials属性:配置是否允许发送Cookie,用于 凭证请求, 默认不发送cookie。
- methods属性:配置跨域请求支持的方式,如:GET、POST,且一次性返回全部支持的方式。
- maxAge属性:配置预检请求的有效时间, 单位是秒,表示:在多长时间内,不需要发出第二次预检请求。
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.exposedHeaders("access-control-allow-headers",
"access-control-allow-methods",
"access-control-allow-origin",
"access-control-max-age",
"X-Frame-Options")
.maxAge(3600)
.allowCredentials(true);
}
}
方法三
过滤器设置跨域
@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;
}
方法简单实用,望各位收藏