【发布时间】:2020-07-23 22:16:42
【问题描述】:
在 istio-ingressgateway 目标上配置 Jwt 策略时,Cors 预检请求不起作用。
网关
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
name: api-gateway
namespace: foo
spec:
selector:
istio: ingressgateway # use istio default controller
servers:
- port:
number: 80
name: http
protocol: HTTP
hosts:
- "api.example.com"
tls:
httpsRedirect: true # sends 301 redirects for http requests
- port:
number: 443
name: https
protocol: HTTPS
tls:
mode: SIMPLE
serverCertificate: /etc/istio/ingressgateway-certs/tls.crt
privateKey: /etc/istio/ingressgateway-certs/tls.key
hosts:
- "api.example.com"
虚拟服务
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: backend-vs
namespace: foo
spec:
hosts:
- "api.example.com"
gateways:
- api-gateway
http:
- match:
- uri:
prefix: /api/v1/info
route:
- destination:
host: backend.foo.svc.cluster.local
corsPolicy:
allowOrigin:
- "https://app.example.com"
allowMethods:
- POST
- GET
- PUT
- DELETE
- PATCH
- OPTIONS
allowHeaders:
- authorization
- content-type
- accept
- origin
- user-agent
allowCredentials: true
maxAge: 300s
安全
apiVersion: "security.istio.io/v1beta1"
kind: "RequestAuthentication"
metadata:
name: "jwt-example"
namespace: foo
spec:
selector:
matchLabels:
app: backend
jwtRules:
- issuer: "http://keycloak.foo/auth/realms/example"
jwksUri: "http://keycloak.foo/auth/realms/example/protocol/openid-connect/certs"
---
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
name: require-jwt-example
namespace: foo
spec:
selector:
matchLabels:
app: backend
action: ALLOW
rules:
- from:
- source:
requestPrincipals: ["http://keycloak.foo/auth/realms/example/http://keycloak.foo/auth/realms/example"]
when:
- key: request.auth.claims[groups]
values: ["group1"]
当我在 firefox 中测试 web 应用程序时,它运行良好,但在其他浏览器(如 opera、chrome、safari)中,它失败并出现以下错误:
Access to XMLHttpRequest at 'https://api.example.com/api/v1/info' from origin 'https://app.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
让我更深思的是因为在firefox中它运行良好,但在其他浏览器中却失败了
注意:为了验证 Istio 中的 cors 策略是否正确,我所做的是在 istio 中禁用此策略并在 firefox 中测试以查看发生了什么,结果是 cors 有问题确实出来了,但是当我在 Firefox 中重新运行时重新启用 istio 中的 cors 时,请求工作正常。
【问题讨论】:
-
如果它在某些浏览器中工作但在其他浏览器中失败,最可能的原因是浏览器扩展。因此,请确保在禁用所有浏览器扩展的情况下进行测试。 Adblock 是一种扩展,尤其是它通常是脚本请求失败的原因。
-
禁用所有 chrome 扩展,它不起作用,问题仍然存在,奇怪的是我在 safari 中没有扩展,它也不起作用。
标签: kubernetes google-cloud-platform cors keycloak istio