Access-Control-Allow-Origin Multiple Origin Domains?

前端 未结 30 2062
隐瞒了意图╮
隐瞒了意图╮ 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

    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

     
          
        JAX-RS Servlet
        com.sun.jersey.spi.container.servlet.ServletContainer
         
            com.sun.jersey.api.json.POJOMappingFeature
            true
        
        
          com.sun.jersey.spi.container.ContainerResponseFilters
          com.your.package.CORSResponseFilter
           
        
            com.sun.jersey.config.property.packages
            com.your.package
                
        1
      
      
        JAX-RS Servlet
        /ws/*
      
    

    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 allowedOrigins = new HashSet(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;
    }
    
    }
    

提交回复
热议问题