Cors筛选器-允许所有子域 [英] Cors Filter - Allow all sub domains

查看:73
本文介绍了Cors筛选器-允许所有子域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的CorsFilter执行以下操作:

I would like my CorsFilter to do the following:

// populating the header required for CORS
response.addHeader(
           "Access-Control-Allow-Origin",
           "https://*.myDomain.com");

整个想法是允许以下域发出请求:sub1.myDomain.com,sub2.myDomain.com,sub3.myDomain.com....sub100.myDomain.com

The whole idea is to allow the following domains to make a request: sub1.myDomain.com, sub2.myDomain.com, sub3.myDomain.com .... sub100.myDomain.com

这对我不起作用.我怎样才能做到这一点?我尝试过:

This didn't work for me. How can I achieve this? Iv'e tried:

response.addHeader(
           "Access-Control-Allow-Origin",
           "*.myDomain.com");

也没有成功.

推荐答案

我遇到了类似的问题,答案是肯定的.

I am having the similar question and the answer is Yes.

这是我的解决方案(根据原始标头处理Access-Control-Allow-Origin)

Here is my solution ( Handling Access-Control-Allow-Origin based on the origin header)

1.从来源"标头中解析主机

    // origin
    String origin = request.getHeader("Origin");

    URL originUrl = null;
    try {
        originUrl = new URL(origin);
    } catch (MalformedURLException ex) {
    }

    // originUrl.getHost() -> Return the host need to be verified

2.检查originUrl.getHost()

    // Allow myDomain.com
    // Or anySubDomain.myDomain.com
    // Or subSub.anySubDomain.myDomain.com

    // hostAllowedPattern 
    Pattern hostAllowedPattern = Pattern.compile("(.+\\.)*myDomain\\.com", Pattern.CASE_INSENSITIVE);

    // Allow host?
    if (hostAllowedPattern.matcher(originUrl.getHost()).matches()) {
        response.addHeader("Access-Control-Allow-Origin", origin);

    } else {
        // Throw 403 status OR send default allow
        response.addHeader("Access-Control-Allow-Origin", "https://my_domain.com");
    }

3.结果:

    // If 'origin': https://sub1.myDomain.com  --> Matched
    Access-Control-Allow-Origin: https://sub1.myDomain.com

    // If 'origin': https://sub2.myDomain.com   --> Matched
    Access-Control-Allow-Origin: https://sub2.myDomain.com

    // If 'origin': https://notAllowDomain.com   --> Not Matched
    Access-Control-Allow-Origin: https://my_domain.com

4.其他:

    You need to verify scheme & port too.

这篇关于Cors筛选器-允许所有子域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆