# CORS

`cors` 插件允许你启用[跨源资源共享 (CORS)](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CORS)。CORS 是一种基于 HTTP 头的机制，允许服务器指定除自身以外的任何来源（域、协议或端口），并指示浏览器允许加载来自这些来源的资源。

## 示例[​](#示例 "示例的直接链接")

以下示例展示了如何在不同场景下使用 `cors` 插件配置路由。

### 为路由启用 CORS[​](#为路由启用-cors "为路由启用 CORS的直接链接")

以下示例展示了如何在路由上启用 CORS，以允许从来源列表加载资源。

* Admin API
* ADC
* Ingress Controller

创建一个带有 `cors` 插件的路由：

```
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

    "id": "cors-route",

    "uri": "/anything",

    "plugins": {

      "cors": {

        "allow_origins": "http://sub.domain.com,http://sub2.domain.com",

        "allow_methods": "GET,POST",

        "allow_headers": "headr1,headr2",

        "expose_headers": "ex-headr1,ex-headr2",

        "max_age": 50,

        "allow_credential": true

      }

    },

    "upstream": {

      "nodes": {

        "httpbin.org:80": 1

      },

      "type": "roundrobin"

    }

  }'
```

adc.yaml

```
services:

  - name: cors-service

    routes:

      - name: cors-route

        uris:

          - /anything

        plugins:

          cors:

            allow_origins: "http://sub.domain.com,http://sub2.domain.com"

            allow_methods: "GET,POST"

            allow_headers: "headr1,headr2"

            expose_headers: "ex-headr1,ex-headr2"

            max_age: 50

            allow_credential: true

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览变更并确认仅影响本指南的资源：

```
adc diff -f adc.yaml \

  --include-resource-type service \

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

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

* Gateway API
* APISIX CRD

cors-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: cors-plugin-config

spec:

  plugins:

    - name: cors

      config:

        allow_origins: "http://sub.domain.com,http://sub2.domain.com"

        allow_methods: "GET,POST"

        allow_headers: "headr1,headr2"

        expose_headers: "ex-headr1,ex-headr2"

        max_age: 50

        allow_credential: true

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: cors-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /anything

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: cors-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

将配置应用到集群：

```
kubectl apply -f cors-ic.yaml
```

cors-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixUpstream

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  ingressClassName: apisix

  externalNodes:

  - type: Domain

    name: httpbin.org

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: cors-route

spec:

  ingressClassName: apisix

  http:

    - name: cors-route

      match:

        paths:

          - /anything

      upstreams:

      - name: httpbin-external-domain

      plugins:

      - name: cors

        enable: true

        config:

          allow_origins: "http://sub.domain.com,http://sub2.domain.com"

          allow_methods: "GET,POST"

          allow_headers: "headr1,headr2"

          expose_headers: "ex-headr1,ex-headr2"

          max_age: 50

          allow_credential: true
```

将配置应用到集群：

```
kubectl apply -f cors-ic.yaml
```

❶ `allow_origins`: 配置允许的来源，用逗号分隔。要允许所有来源，请将其设置为 `*`。

❷ `max_age`: 配置结果缓存的最大时间（以秒为单位）。

❸ `allow_credential`: 设置为 `true` 以允许随请求发送凭据（cookie、HTTP 身份认证和客户端 SSL 证书）。如果将其设置为 true，则不能将 `*` 用于其他 cors 属性。

使用允许的来源向路由发送 HEAD 请求：

```
curl "http://127.0.0.1:9080/anything" -H "Origin: http://sub2.domain.com" -I
```

你应该收到 `HTTP/1.1 200 OK` 响应并观察到 CORS 头：

```
...

Access-Control-Allow-Origin: http://sub2.domain.com

Access-Control-Allow-Credentials: true

Server: APISIX/3.8.0

Vary: Origin

Access-Control-Allow-Methods: GET,POST

Access-Control-Max-Age: 50

Access-Control-Expose-Headers: ex-headr1,ex-headr2

Access-Control-Allow-Headers: headr1,headr2
```

使用未允许的来源向路由发送 HEAD 请求：

```
curl "http://127.0.0.1:9080/anything" -H "Origin: http://sub3.domain.com" -I
```

你应该收到 `HTTP/1.1 200 OK` 响应，没有任何 CORS 头：

```
...

Server: APISIX/3.8.0

Vary: Origin
```

### 使用正则匹配来源[​](#使用正则匹配来源 "使用正则匹配来源的直接链接")

以下示例演示了如何使用 `allow_origins_by_regex` 字段通过正则表达式匹配 `allow_origins` 中的来源。

* Admin API
* ADC
* Ingress Controller

创建一个带有 `cors` 插件的路由：

```
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

    "id": "cors-route",

    "uri": "/anything",

    "plugins": {

      "cors": {

        "allow_methods": "GET,POST",

        "allow_headers": "headr1,headr2",

        "expose_headers": "ex-headr1,ex-headr2",

        "max_age": 50,

        "allow_origins_by_regex": [ ".*\\.test.com$" ]

      }

    },

    "upstream": {

      "nodes": {

        "httpbin.org:80": 1

      },

      "type": "roundrobin"

    }

  }'
```

adc.yaml

```
services:

  - name: cors-service

    routes:

      - name: cors-route

        uris:

          - /anything

        plugins:

          cors:

            allow_methods: "GET,POST"

            allow_headers: "headr1,headr2"

            expose_headers: "ex-headr1,ex-headr2"

            max_age: 50

            allow_origins_by_regex:

              - ".*\\.test.com$"

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览变更并确认仅影响本指南的资源：

```
adc diff -f adc.yaml \

  --include-resource-type service \

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

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

* Gateway API
* APISIX CRD

cors-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: cors-regex-plugin-config

spec:

  plugins:

    - name: cors

      config:

        allow_methods: "GET,POST"

        allow_headers: "headr1,headr2"

        expose_headers: "ex-headr1,ex-headr2"

        max_age: 50

        allow_origins_by_regex:

          - ".*\\.test.com$"

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: cors-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /anything

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: cors-regex-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

将配置应用到集群：

```
kubectl apply -f cors-ic.yaml
```

cors-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixUpstream

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  ingressClassName: apisix

  externalNodes:

  - type: Domain

    name: httpbin.org

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: cors-route

spec:

  ingressClassName: apisix

  http:

    - name: cors-route

      match:

        paths:

          - /anything

      upstreams:

      - name: httpbin-external-domain

      plugins:

      - name: cors

        enable: true

        config:

          allow_methods: "GET,POST"

          allow_headers: "headr1,headr2"

          expose_headers: "ex-headr1,ex-headr2"

          max_age: 50

          allow_origins_by_regex:

            - ".*\\.test.com$"
```

将配置应用到集群：

```
kubectl apply -f cors-ic.yaml
```

❶ `allow_origins_by_regex`：使用正则表达式允许来源，而不是通过 `allow_origins` 进行字面匹配。如果配置了 `allow_origins_by_metadata`，会先评估通过它选定的命名来源，再评估这些正则表达式。

使用允许的来源向路由发送 HEAD 请求：

```
curl "http://127.0.0.1:9080/anything" -H "Origin: http://a.test.com" -I
```

你应该收到 `HTTP/1.1 200 OK` 响应并观察到 CORS 头：

```
...

Access-Control-Allow-Origin: http://a.test.com

Access-Control-Allow-Credentials: true

Server: APISIX/3.8.0

Access-Control-Allow-Methods: GET,POST

Access-Control-Max-Age: 50

Access-Control-Expose-Headers: ex-headr1,ex-headr2

Access-Control-Allow-Headers: headr1,headr2
```

你也可以尝试使用无效的来源发出请求：

```
curl "http://127.0.0.1:9080/anything" -H "Origin: http://a.test2.com" -I
```

你应该收到 `HTTP/1.1 200 OK` 响应，没有任何 CORS 头：

```
...

Server: APISIX/3.8.0

Vary: Origin
```

### 在插件元数据中配置来源[​](#在插件元数据中配置来源 "在插件元数据中配置来源的直接链接")

以下示例演示了如何在[插件元数据](https://docs.apiseven.com/apisix/key-concepts/plugin-metadata.md)中配置来源，并在 `cors` 插件中将其引用为允许的来源。

* Admin API
* ADC
* Ingress Controller

为 `cors` 插件配置插件元数据：

```
curl "http://127.0.0.1:9180/apisix/admin/plugin_metadata/cors" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

    "allow_origins": {

      "key_1": "https://domain.com",

      "key_2": "https://sub.domain.com,https://sub2.domain.com",

      "key_3": "*"

    }

  }'
```

❶ `allow_origins` : 键和允许来源的映射。键将用于匹配路由中的来源。

使用 `allow_origins_by_metadata` 创建一个带有 `cors` 插件的路由：

```
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

    "id": "cors-route",

    "uri": "/anything/cors-metadata",

    "plugins": {

      "cors": {

        "allow_methods": "GET,POST",

        "allow_headers": "headr1,headr2",

        "expose_headers": "ex-headr1,ex-headr2",

        "max_age": 50,

        "allow_origins_by_metadata": ["key_1"]

      }

    },

    "upstream": {

      "nodes": {

        "httpbin.org:80": 1

      },

      "type": "roundrobin"

    }

  }'
```

❶ `allow_origins_by_metadata`: 元数据中用于匹配来源的键。

导出完整的插件元数据集合：

```
adc dump -o metadata.yaml --with-id --include-resource-type plugin_metadata
```

在导出的文件中添加以下来源，并保留其他元数据条目及已有来源：

metadata.yaml

```
plugin_metadata:

  cors:

    allow_origins:

      key_1: "https://domain.com"

      key_2: "https://sub.domain.com,https://sub2.domain.com"

      key_3: "*"
```

❶ `allow_origins`：键与允许来源的映射。路由引用这些键。

预览元数据变更，并确认没有修改或删除无关条目：

```
adc diff -f metadata.yaml --include-resource-type plugin_metadata
```

同步已检查的元数据：

```
adc sync -f metadata.yaml --include-resource-type plugin_metadata
```

创建引用这些来源的服务和路由：

adc.yaml

```
services:

  - name: cors-metadata-service

    labels:

      example: cors-metadata

    routes:

      - name: cors-metadata-route

        uris:

          - /anything/cors-metadata

        plugins:

          cors:

            allow_methods: "GET,POST"

            allow_headers: "headr1,headr2"

            expose_headers: "ex-headr1,ex-headr2"

            max_age: 50

            allow_origins_by_metadata:

              - "key_1"

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

❶ `allow_origins_by_metadata`：元数据中用于匹配来源的键。

预览此示例的服务变更：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector example=cors-metadata
```

同步已检查的服务配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector example=cors-metadata
```

更新 `GatewayProxy` 清单以配置插件元数据：

gatewayproxy.yaml

```
apiVersion: apisix.apache.org/v1alpha1

kind: GatewayProxy

metadata:

  namespace: aic

  name: apisix-config

spec:

  provider:

    type: ControlPlane

    controlPlane:

      # ...

      # 你的控制面连接配置

  pluginMetadata:

    cors:

      allow_origins:

        key_1: "https://domain.com"

        key_2: "https://sub.domain.com,https://sub2.domain.com"

        key_3: "*"
```

❶ `allow_origins`：由键和允许的源组成的映射。该键用于匹配路由中的源。

* Gateway API
* APISIX CRD

创建配置了 `allow_origins_by_metadata` 的路由：

cors-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: cors-metadata-plugin-config

spec:

  plugins:

    - name: cors

      config:

        allow_methods: "GET,POST"

        allow_headers: "headr1,headr2"

        expose_headers: "ex-headr1,ex-headr2"

        max_age: 50

        allow_origins_by_metadata:

          - "key_1"

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: cors-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /anything/cors-metadata

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: cors-metadata-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

创建配置了 `allow_origins_by_metadata` 的路由：

cors-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixUpstream

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  ingressClassName: apisix

  externalNodes:

  - type: Domain

    name: httpbin.org

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: cors-route

spec:

  ingressClassName: apisix

  http:

    - name: cors-route

      match:

        paths:

          - /anything/cors-metadata

      upstreams:

      - name: httpbin-external-domain

      plugins:

      - name: cors

        enable: true

        config:

          allow_methods: "GET,POST"

          allow_headers: "headr1,headr2"

          expose_headers: "ex-headr1,ex-headr2"

          max_age: 50

          allow_origins_by_metadata:

            - "key_1"
```

❶ `allow_origins_by_metadata`: 元数据中用于匹配来源的键。

将配置应用到集群：

```
kubectl apply -f gatewayproxy.yaml -f cors-ic.yaml
```

使用允许的来源向路由发送 HEAD 请求：

```
curl "http://127.0.0.1:9080/anything/cors-metadata" -H "Origin: https://domain.com" -I
```

你应该收到 `HTTP/1.1 200 OK` 响应并观察到 CORS 头：

```
...

Access-Control-Allow-Origin: https://domain.com

Access-Control-Allow-Credentials: true

Server: APISIX/3.8.0

Access-Control-Allow-Methods: GET,POST

Access-Control-Max-Age: 50

Access-Control-Expose-Headers: ex-headr1,ex-headr2

Access-Control-Allow-Headers: headr1,headr2 
```

使用无效的来源发送另一个请求：

```
curl "http://127.0.0.1:9080/anything/cors-metadata" -H "Origin: http://a.test2.com" -I
```

你应该收到 `HTTP/1.1 200 OK` 响应，且没有上方高亮的四个 CORS 响应头。插件不会移除上游返回的响应头，因此响应中仍可能出现其他 CORS 响应头。
