Spring @CrossOrigin 通配符 解决跨域问题

@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"
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值