跳到主要内容
版本:3.10.x

配置 CORS

跨源资源共享(CORS)是一种安全机制,允许 Web 浏览器向不同于原始网页来源的域发出请求。cors插件通过在网关上处理必要的请求头来简化该过程。

本指南介绍常见 CORS 工作流。有关完整插件字段参考、正则表达式匹配和插件元数据选项,请参阅 cors

前置条件

  • API7 企业版实例正在运行。
  • 已创建网关组且网关实例正在运行。
  • 一个 Dashboard Token

配置基本 CORS

以下配置使用默认方法和请求头,允许来自任何源的请求。

curl -k "https://localhost:7443/apisix/admin/services/cors-service?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"name": "cors-service",
"upstream": {
"type": "roundrobin",
"scheme": "http",
"nodes": [
{
"host": "httpbin.org",
"port": 80,
"weight": 100
}
]
}
}'

curl -k "https://localhost:7443/apisix/admin/routes/cors-route?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"name": "cors-route",
"methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
"paths": ["/get"],
"service_id": "cors-service",
"plugins": {
"cors": {
"allow_origins": "*",
"allow_methods": "GET,POST,PUT,DELETE,OPTIONS",
"allow_headers": "*",
"max_age": 3600
}
}
}'

配置带凭据的安全 CORS

要允许 Cookie 或授权请求头等凭据,必须指定允许的源,并将 allow_credential 设置为 true

curl -k "https://localhost:7443/apisix/admin/services/credentialed-cors-service?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"name": "credentialed-cors-service",
"upstream": {
"type": "roundrobin",
"scheme": "http",
"nodes": [
{
"host": "httpbin.org",
"port": 80,
"weight": 100
}
]
}
}'

curl -k "https://localhost:7443/apisix/admin/routes/credentialed-cors-route?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"name": "credentialed-cors-route",
"methods": ["GET", "POST", "OPTIONS"],
"paths": ["/get"],
"service_id": "credentialed-cors-service",
"plugins": {
"cors": {
"allow_origins": "https://example.com,https://api.example.com",
"allow_methods": "GET,POST",
"allow_credential": true,
"expose_headers": "X-Custom-Header",
"max_age": 600
}
}
}'

验证配置

可以使用 curl 模拟 CORS 预检请求:

curl -i -X OPTIONS "http://127.0.0.1:9080/get" \
-H "Origin: https://example.com" \
-H "Access-Control-Request-Method: POST"

响应应根据配置包含 Access-Control-Allow-OriginAccess-Control-Allow-Methods 等请求头。

如果应用配置后路由立即返回 404,请等待几秒,让最新配置下发到网关后重试。

后续步骤