1.通过filter进行定义cors配置,设置优先级大于其他权限处理filter
@Configuration
public class CorsFilterBean {
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
@Bean
public FilterRegistrationBean registCorsFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean(corsFilter());
//优先处理
registration.setOrder(0);
return registration;
}
}
2.全局配置
@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**").allowedOrigins("*")
.allowedHeaders("*").allowedMethods("*");
}
}
3.使用注解@CrossOrigin进行配置
@CrossOrigin
ajax跨域时如果包含自定义请求头时会首先发送OPTIONS的预检请求,当请求满足时才会再次发送实际请求
如果配置了cors参数时,存在自定义请求头的权限验证,若未采用第一种方式,ajax将无法直接访问到后续的cors处理,此时需要进行放行ajax的预检方法,最后交给spring处理
String method = request.getMethod();
if (method.equals("OPTIONS")) {
filterChain.doFilter(servletRequest, servletResponse);
}
注: 经测试spring同时支持该三种方式的控制,filter的优先级大于另外两种配置方式,只要满足其中一种即可
HTTP访问控制(cors)介绍
也可以直接通过设置请求头参数
response.setHeader(“Access-Control-Allow-Origin”, “*”);
response.setHeader(“Access-Control-Allow-Headers”, “*”);
//允许的访问方法
response.setHeader(“Access-Control-Allow-Methods”, “POST, GET, PUT, OPTIONS, DELETE, PATCH”);
//Access-Control-Max-Age 用于 CORS 相关配置的缓存
response.setHeader(“Access-Control-Max-Age”, “3600”);
response.setContentType(“text/html; charset=utf-8”);