@CrossOrigin 通配符 解决跨域问题
痛点:
对很多api接口需要 开放H5 Ajax跨域请求支持 由于环境多套域名不同,而CrossOrigin 原生只支持* 或者具体域名的跨域支持 所以想让CrossOrigin 支持下通配 *.abc.com 支持所有origin 为 abc.com域(包括各种子域名)名来的Ajax 请求支持跨域.
解决思路:
支持通配
@CrossOrigin(origins = {"*.abc.com"}) 通配 主域+任意子域 www.abc.com order.api.abc.com dev.order.abc.com 等
@CrossOrigin(origins = {"*.order.abc.com"}) 通配order子域 子域名 dev.order.abc.com test.order.abc.com uat.order.abc.com 等
Spring 默认支持cors 拓展下 Spring 对跨域的处理类
解决方案:
获取 RequestMappingHandlerMapping 设置自定义 MyCorsProcessor 代替DefaultCorsProcessor
/**
* 给requestMappingHandlerMapping 对象注入自定义 MyCorsProcessor
* @author tomas
* @create 2019/8/12
**/
@Configuration
@EnableWebMvc
public class MyWebMvcConfig extends DelegatingWebMvcConfiguration {
@Bean
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping();
handlerMapping.setCorsProcessor(new MyCorsProcessor());
return handlerMapping;
}
}
/**
* MyCorsProcessor 描述
* 自定义 如果xxx.com域下的请求允许跨域
*
* @author tomas
* @create 2019/8/12
**/
public class MyCorsProcessor extends DefaultCorsProcessor {
/**
* Check the origin of the request against the configured allowed origins.
* @param requestOrigin the origin to check
* @return the origin to use for the response, or {@code null} which
* means the request origin is not allowed
*/
@Nullable
public String checkOrigin(CorsConfiguration config, @Nullable String requestOrigin) {
if (!StringUtils.hasText(requestOrigin)) {
return null;
}
if (ObjectUtils.isEmpty(config.getAllowedOrigins())) {
return null;
}
if (config.getAllowedOrigins().contains(CorsConfiguration.ALL)) {
if (config.getAllowCredentials() != Boolean.TRUE) {
return CorsConfiguration.ALL;
}
else {
return requestOrigin;
}
}
AntPathMatcher pathMatcher = new AntPathMatcher("|");
for (String allowedOrigin :config.getAllowedOrigins()) {
if (requestOrigin.equalsIgnoreCase(allowedOrigin)) {
return requestOrigin;
}
//推荐方式:正则 注意(CrossOrigin(origins = {"*.abc.com"}) ) 主域会匹配主域+子域 origins = {"*.pay.abc.com"