当响应为 401 时,如何为 Kubernetes Ingress Nginx auth-url 设置 CORS?

How to setup CORS for Kubernetes Ingress Nginx auth-url when response is 401?

我的 Kubernetes Ingress 设置如下:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: api
  namespace: staging
  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/rewrite-target: /hello/
    nginx.ingress.kubernetes.io/enable-cors: "true"
    nginx.ingress.kubernetes.io/auth-url: http://external-auth/authenticate
    nginx.ingress.kubernetes.io/auth-response-headers: X-MemberId
    nginx.ingress.kubernetes.io/auth-method: GET
    nginx.ingress.kubernetes.io/configuration-snippet: |
      error_page 401 = @unauthorized;
    nginx.ingress.kubernetes.io/server-snippet: |
      location @unauthorized {
        return 401 "Unauthorized";
      }
spec:
  ...

当请求成功通过身份验证时,CORS 工作正常,但当身份验证失败时(external-auth 以 HTTP 401 响应)似乎没有 CORS headers 随响应一起发送。

我已尝试配置我的外部身份验证服务以也响应 CORS headers,但 nginx 似乎正在删除这些 headers.

有人知道如何设置吗?

我设法解决了我自己的问题。存在该问题是因为我为 HTTP 401 配置了一个自定义错误页面,其中包含以下两行:

nginx.ingress.kubernetes.io/configuration-snippet: |
  error_page 401 = @unauthorized;
nginx.ingress.kubernetes.io/server-snippet: |
  location @unauthorized {
    return 401 "Unauthorized";
  }

如果我设置自定义错误页面nginx.ingress.kubernetes.io/enable-cors: "true"将不会对 401 响应生效。

解决方法是修改自定义错误页面位置,配置如下:

nginx.ingress.kubernetes.io/server-snippet: |
  location @unauthorized {
    # cors for 401 responses
    add_header "Access-Control-Allow-Origin" "*" always;
    return 401 "Unauthorized";
  }

这解决了问题!