spring boot 官网跨域一般的解决方案 有2个:
1.添加拦截器
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*","null")
.allowCredentials(true)
.allowedMethods("GET", "POST","OPTIONS")
.maxAge(3600);
}
这个方法是在运行的时候,HandlerExecutionChain 会根据根据是否是跨域请求,来动态的添加拦截器,使用这个方法可能有问题,因为这个拦截器是最后执行的,跨域请求时,第一次发送的预请求是不会添加额外的header和参数,前面加的权限验证可能把这个当做是未登陆的请求,直接结束请求。
@Nullable
public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
Object handler = this.getHandlerInternal(request);
if (handler == null) {
handler = this.getDefaultHandler();
}
if (handler == null) {
return null;
} else {
if (handler instanceof String) {
String handlerName = (String)handler;
handler = this.obtainApplicationContext().getBean(handlerName);
}
HandlerExecutionChain executionChain = this.getHandlerExecutionChain(handler, request);
//判断是否是跨域请求,如果是就增加拦截器
if (CorsUtils.isCorsRequest(request)) {
CorsConfiguration globalConfig = this.globalCorsConfigSource.getCorsConfiguration(request);
CorsConfiguration handlerConfig = this.getCorsConfiguration(handler, request);
CorsConfiguration config = globalConfig != null ? globalConfig.combine(handlerConfig) : handlerConfig;
executionChain = this.getCorsHandlerExecutionChain(request, executionChain, config);
}
return executionChain;
}
}
2 添加过滤器
@Bean
FilterRegistrationBean corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
//Origin 可以配置 多个 ,* 表示所有
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
CorsFilter filter = new CorsFilter(source);
FilterRegistrationBean registration = new FilterRegistrationBean(filter);
registration.addUrlPatterns("/*");
return registration;
}
这个只要放在权限验证的过滤器之前执行 ,就行。