【问题标题】:How to do CORS the right way?如何以正确的方式进行 CORS?
【发布时间】:2018-05-06 02:08:07
【问题描述】:

我的目标是将 Web 应用程序的访问权限限制为没有来源 = http://localhost:3000 的任何请求

所以在互联网上搜索了一下之后,我能够提出(好吧,复制粘贴)这个配置:

location / {
    set $cors '';
    if ($http_origin ~ 'http://localhost:3000') {
        set $cors 'true';
    }

    if ($cors = 'true') {
        add_header 'Access-Control-Allow-Origin' "$http_origin" always;
        add_header 'Access-Control-Allow-Credentials' 'true' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, PATCH, DELETE, PATCH, OPTIONS' always;
        add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;
    }

    if ($request_method = 'OPTIONS') {
        # Tell client that this pre-flight info is valid for 20 days
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        return 204;
    }

     proxy_pass http://10.131.20.142:8000/131j3yc1;
     proxy_set_header received-from "nginx";
     access_log /dev/stdout upstream_log;
}

我对其进行了测试以了解它的行为方式。当我发送一个来自 http://localhost:3000 的请求时,它会发送带有 CORS 标头的 200 OK。当我发送没有来源或不同来源的请求时,它仍然发送 200 OK 但没有 CORS 标头。当浏览器获取带有 CORS 标头的响应时,它可以正常工作,但是当 CORS 标头不存在时,它会引发如下异常:

我想了解这个 CORS 配置在这里保护什么?

  1. 来源是简单的标头 - 任何人都可以通过 nginx/curl 发送任何来源
  2. 即使您发送错误或无来源,您仍然会获得 200 的数据

我猜我的配置是错误的,因为它不能有效地保护应用免受跨源请求,或者我对 CORS 的理解不正确。

有人可以帮我弄清楚我在做什么/理解错了吗?

【问题讨论】:

  • 你看过Enable-CORS.org吗?
  • 不清楚你期待什么行为,这对我来说似乎是正确的。但请注意,您通常不会仅为来自允许域的请求设置 CORS 标头,并且您对所需行为的描述并不是 CORS 的真正含义。
  • 确保在测试配置时禁用缓存,Access-Control-Max-Age 会导致缓存可能误导您
  • CORS 配置不是导致服务器阻止请求的方法。相反,它只是服务器告诉浏览器是否希望浏览器允许前端 JavaScript 代码访问来自跨域请求的响应的一种方式。见stackoverflow.com/questions/45069689/…stackoverflow.com/questions/43432743/…

标签: javascript http security nginx cors


【解决方案1】:

尝试使用 more_set_headers 代替 add_header

more_set_headers 'Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, PATCH, OPTIONS';
more_set_headers 'Access-Control-Allow-Headers:Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With';
etc

more_set_headers 指令是 HttpHeadersMore 模块的一部分,该模块包含在 nginx 的 nginx-extras flavor 中,您可以通过以下操作将其安装在 ubuntu 16 上:

sudo apt-get install nginx-extras

【讨论】:

    猜你喜欢
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 2014-02-27
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 2019-03-17
    相关资源
    最近更新 更多