CORS:启用 credentials 时通配符失效

规则

当跨域请求的凭据模式为 include 时,不能依赖以下三个响应头中的 * 实现通配匹配:

响应头 Kong 配置字段 携带凭据时 * 的含义
Access-Control-Allow-Origin origins 不允许使用 *,必须返回与请求 Origin 匹配的具体源
Access-Control-Allow-Headers headers 按字面字符串 * 处理,不作为通配符
Access-Control-Expose-Headers exposed_headers 按字面字符串 * 处理,不作为通配符

这里的 credentials: true 是 Kong CORS 插件配置,用于允许凭据访问;浏览器 Fetch 对应的请求选项是 credentials: 'include',不是 credentials: true。

症状

  • OPTIONS 预检请求失败,浏览器报告 CORS 错误。
  • 配置了 origins: ["*"] 或 headers: ["*"],跨域请求仍不通过。
  • exposed_headers: ["*"] 不能让携带凭据的请求读取任意响应头;应显式列出需要暴露的非 CORS 安全列出的响应头。

原因

1
2
3
4
5
6
7
8
9
10
11
浏览器准备发送 credentials: 'include' 的跨域请求:

OPTIONS 预检请求头:
Access-Control-Request-Headers: Content-Type, apikey

服务器响应(错误):
Access-Control-Allow-Headers: *
Access-Control-Allow-Credentials: true

浏览器判断:
"*" 不能代表 Content-Type、apikey → 预检失败

预检检查需考虑后续实际请求的凭据模式;OPTIONS 预检本身通常不携带凭据,不能仅凭 OPTIONS 是否带 Cookie 判断通配符是否适用。

修复方法

必须显式列举具体值:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 错误
config:
origins:
- "*"
headers:
- "*"
credentials: true

# 正确
config:
origins:
- "https://frontend.example.com"
headers:
- "Content-Type"
- "apikey"
credentials: true

如果前端还需要读取特定的非 CORS 安全列出的响应头,也应通过 exposed_headers 显式列出,而不是依赖 *。

示例案例(Kong CORS 插件)

以下域名、服务名及插件名均为示例,不对应真实环境。

场景:前端 https://frontend.example.com 使用 credentials: 'include' 调用 https://api.example.com/example-service。

问题:request-cors-example 插件配置 headers: ["*"],OPTIONS 预检失败。

修复:在 Origin 已正确配置的前提下,改为 headers: ["Content-Type", "apikey"],预检通过。

参考