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

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

举个例子,是这样的:

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

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

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


当前回答

下面是一个Java web应用的解决方案,基于yesthatguy的回答。

我使用的是Jersey REST 1.x

配置web.xml以识别Jersey REST和CORSResponseFilter

<!-- Jersey REST config -->
<servlet>
  <servlet-name>JAX-RS Servlet</servlet-name>
  <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
  <init-param>
    <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
    <param-value>true</param-value>
  </init-param>
  <init-param>
    <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
    <param-value>com.your.package.CORSResponseFilter</param-value>
  </init-param>
  <init-param>
    <param-name>com.sun.jersey.config.property.packages</param-name>
    <param-value>com.your.package</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>JAX-RS Servlet</servlet-name>
  <url-pattern>/ws/*</url-pattern>
</servlet-mapping>

下面是CORSResponseFilter的代码

import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;


public class CORSResponseFilter implements ContainerResponseFilter{

    @Override
    public ContainerResponse filter(ContainerRequest request,
            ContainerResponse response) {
        
        String[] allowDomain = {"http://localhost:9000","https://my.domain.example"};
        Set<String> allowedOrigins = new HashSet<String>(Arrays.asList (allowDomain));                  
        
        String originHeader = request.getHeaderValue("Origin");
        
        if(allowedOrigins.contains(originHeader)) {
            response.getHttpHeaders().add("Access-Control-Allow-Origin", originHeader);
                        
            response.getHttpHeaders().add("Access-Control-Allow-Headers",
                    "origin, content-type, accept, authorization");
            response.getHttpHeaders().add("Access-Control-Allow-Credentials", "true");
            response.getHttpHeaders().add("Access-Control-Allow-Methods",
                    "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        }
        
        return response;
    }
}

其他回答

只能为Access-Control-Allow-Origin标头指定一个原点。但是您可以根据请求在响应中设置原点。不要忘记设置Vary标头。在PHP中,我将做以下工作:

/**
 * Enable CORS for the passed origins.
 * Adds the Access-Control-Allow-Origin header to the response with the origin that matched the one in the request.
 * @param array $origins
 * @return string|null returns the matched origin or null
*/
function allowOrigins($origins)
{
    $val = $_SERVER['HTTP_ORIGIN'] ?? null;
    if (in_array($val, $origins, true)) {
        header('Access-Control-Allow-Origin: '.$val);
        header('Vary: Origin');
        
        return $val;
    }
        
    return null;
}
    
if (allowOrigins(['http://localhost', 'https://localhost'])) {
   echo your response here, e.g. token
}

对于多个域,在你的。htaccess:

<IfModule mod_headers.c>
    SetEnvIf Origin "http(s)?://(www\.)?(domain1.example|domain2.example)$" AccessControlAllowOrigin=$0$1
    Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    Header set Access-Control-Allow-Credentials true
</IfModule>

Django中还有一个答案。要让一个视图允许来自多个域的CORS,以下是我的代码:

def my_view(request):
    if 'HTTP_ORIGIN' in request.META.keys() and request.META['HTTP_ORIGIN'] in ['http://allowed-unsecure-domain.com', 'https://allowed-secure-domain.com', ...]:
        response = my_view_response() # Create your desired response data: JsonResponse, HttpResponse...
        # Then add CORS headers for access from delivery
        response["Access-Control-Allow-Origin"] = request.META['HTTP_ORIGIN']
        response["Access-Control-Allow-Methods"] = "GET" # "GET, POST, PUT, DELETE, OPTIONS, HEAD"
        response["Access-Control-Max-Age"] = "1000"  
        response["Access-Control-Allow-Headers"] = "*"  
        return response

我努力为一个运行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

谷歌对通过SSL服务广告的支持回答和RFC本身的语法似乎表明您可以用空格分隔url。不知道这在不同的浏览器中有多受支持。