Java - Access-Control-Allow-Origin多个源域?

时间:2016-08-16 20:31:32

标签: java http-headers xmlhttprequest

所以我已经阅读了其他相关内容并且没有找到解决方案。

我遇到的问题是因为我正在设置" access-control-allow-methods" "真"我不能使用setHeader("Access-Control-Allow-Origin", "*");

我需要设置两个特定的域...任何帮助都表示赞赏。

4 个答案:

答案 0 :(得分:2)

您可以做的是将您的http方法修改为:

 public Response getYourMethod( HttpServletRequest request) 
                             throws Exception, IOException{
  //then your code
 }

在此之后添加以下内容:

由于您的API在Allow Origin Header中查找www.yoursite.com:3000,因此您需要确保在以下行中添加此内容:

response.setHeader("Access-Control-Allow-Origin", "www.yoursite.com:3000");

要获得www.yoursite.com:3000,您可以使用:

String requestUrl = request.getRemoteAddr() + ":" + request.getRemotePort();

但是如果浏览器寻找localhost,那么请转到:

request.getRemoteHost().

所以你基本上可以这样:

if (requestUrl.equals(yourAPIURL)){
   //allow access
    response.setHeader("Access-Control-Allow-Origin", requestUrl);
}

避免添加*,因为如果您使用浏览器,某些浏览器和API仍然不允许这样做,并且可能会被预检请求拒绝。

确保按照帖子中的说明正确添加标题和方法。

希望能解决你的问题。

答案 1 :(得分:1)

public class CorsInterceptor implements ContainerResponseFilter {
    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
            throws IOException {
        //Cuando se envia la cookie http-only el header 'Access-Control-Allow-Origin' no puede ser *
        responseContext.getHeaders().putSingle("Access-Control-Allow-Origin", requestContext.getHeaderString("origin"));
    }
}

答案 2 :(得分:0)

您可以这样做:

private static final String URL = "http://somehost:port"; // URL
private static final String OTHER_URL = "http://otherhost:port"; // OTHER URL  

private void setAccessControlAllowOrigin(HttpServletResponse response,
     HttpServletRequest request) {
    if (URL.equals(request.getHeader("Origin"))) {
        response.setHeader("Access-Control-Allow-Origin", URL);
    } else if (OTHER_URL.equals(request.getHeader("Origin"))) {
        response.setHeader("Access-Control-Allow-Origin", OTHER_URL);
    }
}

答案 3 :(得分:0)

这是我只允许特定来源的方法

  1. .properties 文件中定义一个属性以获取允许来源的值,如下所示
#CORS Settings
cors.origins.allowed=https://127.0.0.1:5500, http://127.0.0.1:5000

实现一个过滤器类,我们可以在其中修改响应允许源头

private String setAllowedOrigin(HttpServletRequest request) {
        String requestOrigin = request.getHeader("origin");
        log.info("Request is received with origin header : {}", requestOrigin);
        List<String> originsList = Arrays.stream(this.origins.split(","))
                .map(String::trim).filter(origin -> !origin.equals("")).collect(Collectors.toList());
        log.info("origins List : {}", originsList);
        if (!originsList.isEmpty() && requestOrigin != null) {
            Optional<String> origin = originsList.stream().filter(allowedOrigin -> allowedOrigin.equals(requestOrigin)).findFirst();
            return origin.orElseGet(() -> originsList.get(0));
        }
        return "*";
    }


 @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", setAllowedOrigin(request));
       
        chain.doFilter(req, res);
    }

这个 CORS 过滤器只允许属性文件中提到的来源 为了说明这种行为,我使用 Visual Studio 代码实时服务器和以下代码,我的 API 中有一个 test 端点。

<!DOCTYPE html>
<html>

<head>
    <title></title>
</head>

<body>
    <Script>
        fetch("http://localhost:8080/test", { method: "get" })
            .then(res => res.json())
            .then(data => console.log(data));
    </Script>
</body>

</html>

Sample Image when I hit the live server