什么是跨域
判断是否跨域可通过以下三点:
三点有其一不满足就会造成跨域。
- 协议相同
- 域名相同
- 端口相同
具体关于什么是跨域,可以看一下阮一峰的 跨域资源共享 CORS 详解
解决CORS
跨域问题
- 首先配置全局跨域
一般前后端项目后端都会配置,也可以使用Nginx配置,vue可以通过配置proxy
/**
* 重写全局web配置
*
* @author Knox
* @date 2020/12/6
*/
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
/**
* 跨域访问配置
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
- 配置
SpringSecurity
除了全局配置,还需要配置springsecurity,使其支持跨域请求
Spring Security 本身是通过 Filter 实现的,如果没有对其单独做 CORS 的处理,在 Web Security 报错 401 的时候是不会返回相应的 CORS 的字段的。这会导致命名应该出现的 401 错误成为了一个无法进行跨域的错误,导致前端程序无法正常的处理 401 相应
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// by default uses a Bean by the name of corsConfigurationSource
.cors().and()
//跨域请求会先进行一次options请求
.antMatchers(HttpMethod.OPTIONS).permitAll()
...
}