Access-Control-Allow-Origin Multiple Origin Domains?

前端 未结 30 2035
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 07:08

Is there a way to allow multiple cross-domains using the Access-Control-Allow-Origin header?

I\'m aware of the *, but it is too open. I rea

相关标签:
30条回答
  • 2020-11-21 07:13

    For IIS 7.5+ with URL Rewrite 2.0 module installed please see this SO answer

    0 讨论(0)
  • 2020-11-21 07:13

    Here's a solution for Java web app, based the answer from yesthatguy.

    I am using Jersey REST 1.x

    Configure the web.xml to be aware of Jersey REST and the 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>
    

    Here's the code for 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;
    }
    
    }
    
    0 讨论(0)
  • 2020-11-21 07:13

    PHP code example for matching subdomains.

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

    And one more answer in Django. To have a single view allow CORS from multiple domains, here is my code:

    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
    
    0 讨论(0)
  • 2020-11-21 07:14

    I struggled to set this up for a domain running HTTPS, so I figured I would share the solution. I used the following directive in my httpd.conf file:

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

    Change example.com to your domain name. Add this inside <VirtualHost x.x.x.x:xx> in your httpd.conf file. Notice that if your VirtualHost has a port suffix (e.g. :80) then this directive will not apply to HTTPS, so you will need to also go to /etc/apache2/sites-available/default-ssl and add the same directive in that file, inside of the <VirtualHost _default_:443> section.

    Once the config files are updated, you will need to run the following commands in the terminal:

    a2enmod headers
    sudo service apache2 reload
    
    0 讨论(0)
  • 2020-11-21 07:14

    AWS Lambda/API Gateway

    For information on how to configure multiple origins on Serverless AWS Lambda and API Gateway - albeit a rather large solution for something one would feel should be quite straightforward - see here:

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


    It is currently not possible to configure multiple origins in API Gateway, see here: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors-console.html), but the recommendation (in the answer above) is:

    • inspect the Origin header sent by the browser
    • check it against a whitelist of origins
    • if it matches, return the incoming Origin as the Access-Control-Allow-Origin header, else return a placeholder (default origin).

    The simple solution is obviously enabling ALL (*) like so:

    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([{
    

    But it might be better to do this on the API Gateway side (see 2nd link above).

    0 讨论(0)
提交回复
热议问题