预检(选项)returns 403,CORS

Preflight (OPTIONS) returns 403, CORS

我们将 Kubernetes 与 Istio 结合使用并配置了虚拟服务:

  http:
  - match:
    - uri:
        prefix: /api
    rewrite:
      uri: /api
    route:
    - destination:
        host: svc-api
        port:
          number: 80
        subset: stable
      weight: 0
    - destination:
        host: svc-api
        port:
          number: 80
        subset: vnext
      weight: 100
    corsPolicy: &apiCorsPolicy
      allowOrigins:
      - exact: '*'
      allowMethods:
      - GET
      - POST
      - OPTIONS
      allowCredentials: true
      allowHeaders:
      - "*"
  - match:
    - uri:
        prefix: /
    rewrite:
      uri: /
    route:
    - destination:
        host: svc-api
        port:
          number: 80
        subset: stable
      weight: 0
    - destination:
        host: svc-api
        port:
          number: 80
        subset: vnext
      weight: 100
    corsPolicy: *apiCorsPolicy

从浏览器向 https://[host]/api/* 发出请求失败,OPTIONS 请求为 'from origin [request] has been blocked by CORS policy'

在 k8 中描述服务显示了正确的配置。

根据 v 1.6.4,使用 allowOriginsexact 而不是 allowOrigin 的结构是正确的。

我在这里错过了什么?

这里有几件事值得一提。


最近在旧的 istio 版本中,cors 和 jwt 结合在一起时出现问题,请查看以下链接:


另一个 github issue about that, in this comment 社区成员有同样的问题,也许值得为此打开一个新的 github 问题?


此外还有来自 istio dev @howardjohn 的回答

Hi everyone. Testing CORS using curl can be a bit misleading. CORS is not enforced at the server side; it will not return a 4xx error for example. Instead, headers are returned back which are used by browsers to deny/accept. https://www.envoyproxy.io/docs/envoy/latest/start/sandboxes/cors.html?highlight=cors gives a good demo of this, and https://www.sohamkamani.com/blog/2016/12/21/web-security-cors/#:~:text=CORS%20isn't%20actually%20enforced,header%20in%20all%20its%20responses. is a good explanation.

So Istio's job here is simply to return these headers. I have added a test showing this works: #26231.


正如我在评论中提到的值得看看另一个社区成员配置 here,因为他有一个可行的选项示例,但 POST.[=21= 有一个 403 问题]


我会在您的虚拟服务中更改一些内容

仅使用 corsPolicy 而不是 corsPolicy: &apiCorsPolicy

corsPolicy:

您还可以使用正则表达式代替精确表达式,这可能会解决通配符问题。

allowOrigins:
- regex: '*'

关于//api路径,我觉得这里前缀就够了,不需要重写。