CORS 允许 * 但仍然在 POST 请求上得到 403

CORS Allows * but still getting a 403 on the POST request

这是我的问题。我的服务器配置为 CORS,预检请求工作正常:

$> curl 'https://db.mywebsite.com/something/_search' -X 'OPTIONS' ...

< HTTP/1.1 200 OK
< Access-Control-Allow-Origin: *
< Allow: GET,POST
< Content-Length: 0
< Content-Type: text/plain; charset=UTF-8
< Date: Tue, 20 Apr 2021 06:18:36 GMT

如您所见,它设置为允许每个来源(因为允许正确的来源不起作用,我尝试使用 *,但问题仍然存在。)

虽然在发出后续实际请求时,这是我得到的:

$> curl 'https://db.mywebsite.com/something/_search' -X 'POST' -H 'origin: https://mywebsite.com/' ...

< HTTP/1.1 403 Forbidden
< Access-Control-Allow-Origin: *
< Content-Length: 0
< Date: Tue, 20 Apr 2021 06:20:02 GMT

有趣的是,如果我删除 origin header,它工作正常,所以这排除了 403 将来自后端服务器。

当我在网上寻找类似问题时,我只遇到预检请求收到 403 错误但找不到与我在这里遇到的类似问题的情况。知道这可能是什么原因吗?

原来这个问题不是我想象的,光看我最初发布的信息是不可能想出来的。万一对任何人都有帮助,发生的事情如下:

数据库是 ElasticSearch,它被配置为使用以下配置启用 CORS:

http:
  cors:
    enabled: true
    allow-credentials: true
    allow-origin: "https://mywebsite.com"
    allow-headers: "X-Requested-With, Content-Type, Content-Length, Authorization"
    allow-methods: "PUT, OPTIONS, POST"

同时,它由 Traefik 提供服务,Traefik 也配置为使用 CORS headers:

  elasticsearch:
    image: elasticsearch:7.12.0
    labels:
      - "traefik.enable=true"
      - "traefik.http.middlewares.addAuth.headers.accesscontrolallowmethods=PUT, OPTIONS, POST"
      - "traefik.http.middlewares.addAuth.headers.accesscontrolalloworiginlist=https://mywebsite.com"
      - "traefik.http.middlewares.addAuth.headers.accesscontrolallowheaders=X-Requested-With, Content-Type, Content-Length, Authorization"
      - "traefik.http.routers.db.middlewares=addAuth"
      - "traefik.http.routers.db.rule=Host(`db.mywebsite.com`)"
      - "traefik.http.routers.db.tls=true"
      - "traefik.http.routers.db.tls.certresolver=myresolver"
      - "traefik.port=9200"

事实证明,同时具有两种配置 运行,Traefik 可以很好地处理预检请求,转发实际请求,然后 ElasticSearch 拒绝它。

简单地删除 ElasticSearch 中的 CORS 配置并依赖 Traefik 解决了这个问题。