# 配置 CORS

跨源资源共享（CORS）是一种安全机制，允许 Web 浏览器向不同于原始网页来源的域发出请求。[`cors`](https://docs.apiseven.com/hub/cors.md) 插件通过在网关上处理必要的 HTTP 标头来简化该过程。

本指南介绍常见 CORS 工作流。有关完整插件字段参考、正则表达式匹配和插件元数据选项，请参阅 [`cors`](https://docs.apiseven.com/hub/cors.md)。

## 前置条件[​](#前置条件 "前置条件的直接链接")

* API7 企业版实例正在运行。
* 已创建网关组且网关实例正在运行。
* 按照[从控制台获取 Token](https://docs.apiseven.com/api7-gateway/reference/obtain-dashboard-token.md)中的步骤准备一个 Token。

## 配置基本 CORS[​](#配置基本-cors "配置基本 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": ["/cors"],

    "service_id": "cors-service",

    "plugins": {

      "proxy-rewrite": {

        "uri": "/get"

      },

      "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:

          - /cors

        methods:

          - GET

          - POST

          - PUT

          - DELETE

          - OPTIONS

        plugins:

          proxy-rewrite:

            uri: /get

          cors:

            allow_origins: "*"

            allow_methods: "GET,POST,PUT,DELETE,OPTIONS"

            allow_headers: "*"

            max_age: 3600

    labels:

      docs-example: cors-service
```

预览本示例管理的资源变更，确认没有非预期的更新或删除：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=cors-service
```

审查变更后同步配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=cors-service
```

## 配置带凭证的安全 CORS[​](#配置带凭证的安全-cors "配置带凭证的安全 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": ["/credentialed-cors"],

    "service_id": "credentialed-cors-service",

    "plugins": {

      "proxy-rewrite": {

        "uri": "/get"

      },

      "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:

          - /credentialed-cors

        methods:

          - GET

          - POST

          - OPTIONS

        plugins:

          proxy-rewrite:

            uri: /get

          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

    labels:

      docs-example: credentialed-cors-service
```

预览本示例管理的资源变更，确认没有非预期的更新或删除：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=credentialed-cors-service
```

审查变更后同步配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=credentialed-cors-service
```

## 验证配置[​](#验证配置 "验证配置的直接链接")

向通配符策略的路由发送预检请求：

```
curl -i -X OPTIONS "http://127.0.0.1:9080/cors" \

  -H "Origin: https://example.com" \

  -H "Access-Control-Request-Method: POST"
```

再向支持凭证的独立路由发送预检请求：

```
curl -i -X OPTIONS "http://127.0.0.1:9080/credentialed-cors" \

  -H "Origin: https://example.com" \

  -H "Access-Control-Request-Method: POST"
```

每个响应都应包含对应路由配置的 `Access-Control-Allow-Origin` 和 `Access-Control-Allow-Methods`。支持凭证的路由还应返回 `Access-Control-Allow-Credentials: true`。

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

## 后续步骤[​](#后续步骤 "后续步骤的直接链接")

* [配置故障注入](https://docs.apiseven.com/api7-gateway/how-to-guides/traffic-management/fault-injection.md)——测试应用韧性。
* [配置代理镜像](https://docs.apiseven.com/api7-gateway/how-to-guides/traffic-management/proxy-mirror.md)——将流量复制到测试环境。
* [配置限流](https://docs.apiseven.com/api7-gateway/how-to-guides/traffic-management/rate-limiting.md)——保护 API 免受滥用。
