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

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

举个例子,是这样的:

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

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

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


当前回答

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

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

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

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

其他回答

我们也可以在全局中设置这个。asax文件用于Asp.net应用程序。

protected void Application_BeginRequest(object sender, EventArgs e)
    {

    // enable CORS
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "https://www.youtube.com");

    }

我努力为一个运行HTTPS的域设置这个,所以我想我会分享这个解决方案。我在我的httpd.conf文件中使用了以下指令:

    <FilesMatch "\.(ttf|otf|eot|woff)$">
            SetEnvIf Origin "^http(s)?://(.+\.)?example\.com$" AccessControlAllowOrigin=$0
            Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    </FilesMatch>

将example.com更改为您的域名。在httpd.conf文件中的<VirtualHost x.x.x.x:xx>中添加此内容。注意,如果你的VirtualHost有一个端口后缀(例如:80),那么这个指令将不适用于HTTPS,所以你还需要去/etc/apache2/sites-available/default-ssl并在那个文件中添加相同的指令,在<VirtualHost _default_:443>部分。

配置文件更新后,需要在终端上执行以下命令:

a2enmod headers
sudo service apache2 reload

为了方便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动词。

AWS Lambda/ fire Gateway

有关如何在无服务器AWS Lambda和API网关上配置多个源的信息-尽管一个相当大的解决方案,但人们会觉得应该非常简单-请参阅这里:

https://stackoverflow.com/a/41708323/1624933


目前不可能在API Gateway中配置多个源,请参阅这里:https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors-console.html),但建议(在上面的回答中)是:

检查浏览器发送的Origin报头 在来源白名单上查一下 如果匹配,返回传入的Origin作为Access-Control-Allow-Origin头,否则返回占位符(默认Origin)。


简单的解决方案显然是可行的 所有(*)像这样:

exports.handler = async (event) => {
    const response = {
        statusCode: 200,
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS
        },
        body: JSON.stringify([{

但是在API网关端做这件事可能会更好(见上面的第二个链接)。

匹配子域的PHP代码示例。

if( preg_match("/http:\/\/(.*?)\.yourdomain.example/", $_SERVER['HTTP_ORIGIN'], $matches )) {
        $theMatch = $matches[0];
        header('Access-Control-Allow-Origin: ' . $theMatch);
}