用于本地主机和暂存的 Cors 过滤器 url

Cors filter for localhost and staging url

我们正在开发一个java-spring mvc 项目。 为了让客户团队能够连接到我们的服务,我们创建了一个 CorsFilter:

  @Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException,
    IOException {

// populating the header required for CORS

String responseURL = this.corsMap.get(request.getServerName().toString());
response.addHeader(
           "Access-Control-Allow-Origin",
           (responseURL == null ? "https://default.ourCompany.com" : responseURL));

response.addHeader(
           "Access-Control-Allow-Credentials",
           "true");

if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
    // CORS "pre-flight" request
    response.addHeader(
               "Access-Control-Allow-Methods",
               "GET, POST, PUT, DELETE");
    response.addHeader(
               "Access-Control-Allow-Headers",
               "X-Requested-With,Origin,Content-Type, Accept");
}

filterChain.doFilter(
             request,
             response);
}

注意事项:

1) 我们允许所有 OPTIONS 传入请求。

2) 我们允许 "Access-Control-Allow-Headers" 的特定 ip(因为 "Access-Control-Allow-Credentials"=true 要求如此)

3) 名为 corsMap 的映射包含所有客户端 url 及其到服务器 url 的映射,如下所示:

10.110.0.55->http://localhost
10.110.0.66->https://some.other.url

现在我们遇到了一个问题:

我们想使用来自“http://localhost" AND from "http://some.other.url”的客户端。我们怎样才能做到这一点? (这里的问题是只允许一个客户端 URL,如果可以从多个 URL 接收客户端请求 - 我们将无法确定允许什么)。

对于跨域请求,请求将具有 "Origin" header,稍后将与 "Access-Control-Allow-Origin" 响应 header(我们在上面的过滤器)。

所以,我认为,如下编码 doFilterInternal 应该可行:

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException,
    IOException {

    String clientURL = request.getHeader("Origin");
    response.addHeader(
           "Access-Control-Allow-Origin",
           isInWhileList(clientURL) ? clientUrl : "https://default.ourCompany.com";
    ...

:

最新版本 Spring 有 a new way 配置 CORS,它有一个 allowedOrigins 方法,可以接受一组列入白名单的 URL。

具体例子也可以参考Spring Lemon的源码