配置 CORS
跨源资源共享(CORS)是一种安全机制,允许 Web 浏览器向不同于原始网页来源的域发出请求。cors插件通过在网关上处理必要的请求头来简化该过程。
本指南介绍常见 CORS 工作流。有关完整插件字段参考、正则表达式匹配和插件元数据选项,请参阅 cors。
前置条件
- API7 企业版实例正在运行。
- 已创建网关组且网关实例正在运行。
- 一个 Dashboard Token。
配置基本 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