是否有一种方法允许多个跨域使用Access-Control-Allow-Origin头?

我知道*,但它太开放了。我只讲几个域。

举个例子,是这样的:

Access-Control-Allow-Origin: http://domain1.example, http://domain2.example

我已经尝试了上面的代码,但它似乎不能在Firefox中工作。

是否可以指定多个域,还是只能指定一个域?


当前回答

为了方便ASMX服务的多域访问,我在全局中创建了这个函数。asax文件:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    string CORSServices = "/account.asmx|/account2.asmx";
    if (CORSServices.IndexOf(HttpContext.Current.Request.Url.AbsolutePath) > -1)
    {
        string allowedDomains = "http://xxx.yyy.example|http://aaa.bbb.example";

        if(allowedDomains.IndexOf(HttpContext.Current.Request.Headers["Origin"]) > -1)
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", HttpContext.Current.Request.Headers["Origin"]);

        if(HttpContext.Current.Request.HttpMethod == "OPTIONS")
            HttpContext.Current.Response.End();
    }
}

这也允许CORS处理OPTIONS动词。

其他回答

我有https://stackoverflow.com/a/7454204/13779574这段代码工作得很好,但当用户进入该页面时给出一个错误。 我用这段代码解决了这个问题。

if (isset($_SERVER['HTTP_ORIGIN'])) {
   $http_origin = $_SERVER['HTTP_ORIGIN'];
   if ($http_origin == "http://localhost:3000" || $http_origin == "http://api.loc/"){  
      header("Access-Control-Allow-Origin: $http_origin");
   }
}

我有同样的问题与woff字体,多子域必须有访问。为了允许子域,我在我的httpd.conf中添加了这样的东西:

SetEnvIf Origin "^(.*\.example\.com)$" ORIGIN_SUB_DOMAIN=$1
<FilesMatch "\.woff$">
    Header set Access-Control-Allow-Origin "%{ORIGIN_SUB_DOMAIN}e" env=ORIGIN_SUB_DOMAIN
</FilesMatch>

对于多个域,您可以更改SetEnvIf中的正则表达式。

为了对. net应用程序进行相当简单的复制/粘贴,我写这个代码是从全局变量中启用CORS。asax文件。这段代码遵循当前接受的回答中给出的建议,将请求中给出的任何原点反映到响应中。这有效地实现了'*'而不使用它。

这样做的原因是它支持多种其他CORS功能,包括发送带有'withCredentials'属性设置为'true'的AJAX XMLHttpRequest的能力。

void Application_BeginRequest(object sender, EventArgs e)
{
    if (Request.HttpMethod == "OPTIONS")
    {
        Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
        Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
        Response.AddHeader("Access-Control-Max-Age", "1728000");
        Response.End();
    }
    else
    {
        Response.AddHeader("Access-Control-Allow-Credentials", "true");

        if (Request.Headers["Origin"] != null)
            Response.AddHeader("Access-Control-Allow-Origin" , Request.Headers["Origin"]);
        else
            Response.AddHeader("Access-Control-Allow-Origin" , "*");
    }
}

对于安装了URL重写2.0模块的iis7.5 +,请参阅此SO答案

下面的答案是针对c#的,但是这个概念应该适用于所有不同的平台。

为了允许来自web api的跨源请求,你需要允许应用程序的选项请求,并在控制器级别添加下面的注释。

[EnableCors UrlString、头、方法) 现在原点只能传递一个s字符串。因此,如果你想在请求中传递多个URL,请以逗号分隔。

UrlString = https://a.hello.com, https://b.hello.com”