配置 CORS
跨源资源共享(CORS)是一种安全机制,允许 Web 浏览器向不同于原始网页来源的域发出请求。cors 插件通过在网关上处理必要的 HTTP 标头来简化该过程。
本指南介绍常见 CORS 工作流。有关完整插件字段参考、正则表达式匹配和插件元数据选项,请参阅 cors。
前置条件
- API7 企业版实例正在运行。
- 已创建网关组且网关实例正在运行。
- 按照从控制台获取令牌中的步骤准备一个令牌。
配置基本 CORS
以下配置使用默认方法和请求头,允许来自任何源的请求。
- Admin API
- ADC
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
}
}
}'
adc.yaml
services:
- name: cors-service
upstream:
nodes:
- host: httpbin.org
port: 80
weight: 1
routes:
- name: cors-route
uris:
- /get
plugins:
cors:
allow_origins: "*"
allow_methods: "GET,POST,PUT,DELETE,OPTIONS"
allow_headers: "*"
max_age: 3600
adc sync -f adc.yaml
配置带凭证的安全 CORS
要允许 Cookie 或授权请求头等凭证,必须指定允许的源,并将 allow_credential 设置为 true。
- Admin API
- ADC
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
}
}
}'
adc.yaml
services:
- name: credentialed-cors-service
upstream:
nodes:
- host: httpbin.org
port: 80
weight: 1
routes:
- name: credentialed-cors-route
uris:
- /get
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
adc sync -f adc.yaml
验证配置
可以使用 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-Origin 和 Access-Control-Allow-Methods 等响应头。
如果应用配置后路由立即返回 404,请等待几秒,让最新配置下发到网关后重试。