# Basic Auth

`basic-auth` 插件为 [消费者 (Consumers)](https://docs.apiseven.com/apisix/key-concepts/consumers.md) 添加 [基本访问认证 (Basic Access Authentication)](https://en.wikipedia.org/wiki/Basic_access_authentication)，以便他们在访问上游资源之前进行身份认证。

消费者成功通过身份认证后，APISIX 会在将请求代理到上游服务之前添加额外的请求头，例如 `X-Consumer-Username`、`X-Credential-Identifier`；如果配置了消费者自定义请求头，也会一并添加。上游服务可以据此区分消费者并执行额外逻辑。如果这些值不可用，则不会添加相应的请求头。

关于 X-Consumer-Username

使用 Ingress Controller 配置消费者时，消费者名称会生成为 `namespace_consumername` 格式。因此，`X-Consumer-Username` 请求头也会采用此格式，而不只是 `consumername`。

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

以下示例展示了如何在不同场景下使用 `basic-auth` 插件。

### 在路由上实现基本认证[​](#在路由上实现基本认证 "在路由上实现基本认证的直接链接")

以下示例展示了如何在路由上实现基本认证。

* Admin API
* ADC
* Ingress Controller

创建一个消费者 `johndoe`：

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

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

  -d '{

    "username": "johndoe"

  }'
```

为该消费者创建 `basic-auth` 凭证：

```
curl "http://127.0.0.1:9180/apisix/admin/consumers/johndoe/credentials" -X PUT \

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

  -d '{

    "id": "cred-john-basic-auth",

    "plugins": {

      "basic-auth": {

        "username": "johndoe",

        "password": "john-key"

      }

    }

  }'
```

创建一个启用 `basic-auth` 的路由：

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

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

  -d '{

    "id": "basic-auth-route",

    "uri": "/anything",

    "plugins": {

      "basic-auth": {}

    },

    "upstream": {

      "type": "roundrobin",

      "nodes": {

        "httpbin.org:80": 1

      }

    }

  }'
```

创建一个配置了 `basic-auth` 凭证的消费者，以及一个配置了 `basic-auth` 插件的路由：

adc.yaml

```
consumers:

  - username: johndoe

    credentials:

      - name: basic-auth

        type: basic-auth

        config:

          username: johndoe

          password: john-key

services:

  - name: basic-auth-service

    routes:

      - name: basic-auth-route

        uris:

          - /anything

        plugins:

          basic-auth: {}

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

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

```
adc diff -f adc.yaml \

  --include-resource-type consumer \

  --include-resource-type service \

  --label-selector docs-example=basic-auth
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type consumer \

  --include-resource-type service \

  --label-selector docs-example=basic-auth
```

创建一个配置了 `basic-auth` 凭证的消费者，以及一个配置了 `basic-auth` 插件的路由：

* Gateway API
* APISIX CRD

basic-auth-ic.yaml

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

kind: Consumer

metadata:

  namespace: aic

  name: johndoe

spec:

  gatewayRef:

    name: apisix

  credentials:

    - type: basic-auth

      name: primary-cred

      config:

        username: johndoe

        password: john-key

---

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: basic-auth-plugin-config

spec:

  plugins:

    - name: basic-auth

      config:

        _meta:

          disable: false

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: basic-auth-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /anything

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: basic-auth-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

将配置应用到集群：

```
kubectl apply -f basic-auth-ic.yaml
```

basic-auth-ic.yaml

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

kind: ApisixConsumer

metadata:

  namespace: aic

  name: johndoe

spec:

  ingressClassName: apisix

  authParameter:

    basicAuth:

      value:

        username: johndoe

        password: john-key

---

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: basic-auth-route

spec:

  ingressClassName: apisix

  http:

    - name: basic-auth-route

      match:

        paths:

          - /anything

      upstreams:

      - name: httpbin-external-domain

      plugins:

      - name: basic-auth

        enable: true
```

将配置应用到集群：

```
kubectl apply -f basic-auth-ic.yaml
```

#### 使用有效凭证进行验证[​](#使用有效凭证进行验证 "使用有效凭证进行验证的直接链接")

使用有效凭证发送请求：

```
curl -i "http://127.0.0.1:9080/anything" -u johndoe:john-key
```

你应该会看到类似以下的 `HTTP/1.1 200 OK` 响应：

```
{

  "args": {}, 

  "headers": {

    "Accept": "*/*", 

    "Authorization": "Basic am9obmRvZTpqb2huLWtleQ==",

    "Host": "127.0.0.1",

    "User-Agent": "curl/8.6.0", 

    "X-Amzn-Trace-Id": "Root=1-66e5107c-5bb3e24f2de5baf733aec1cc",

    "X-Consumer-Username": "johndoe",

    "X-Credential-Identifier": "cred-john-basic-auth",

    "X-Forwarded-Host": "127.0.0.1"

  }, 

  "origin": "192.168.65.1, 205.198.122.37", 

  "url": "http://127.0.0.1/anything"

}
```

#### 使用无效凭证进行验证[​](#使用无效凭证进行验证 "使用无效凭证进行验证的直接链接")

使用无效凭证发送请求：

```
curl -i "http://127.0.0.1:9080/anything" -u johndoe:invalid-password
```

你应该会看到包含以下内容的 `HTTP/1.1 401 Unauthorized` 响应：

```
{"message":"Invalid user authorization"}
```

#### 未提供凭证进行验证[​](#未提供凭证进行验证 "未提供凭证进行验证的直接链接")

未提供凭证发送请求：

```
curl -i "http://127.0.0.1:9080/anything"
```

你应该会看到包含以下内容的 `HTTP/1.1 401 Unauthorized` 响应：

```
{"message":"Missing authorization in request"}
```

### 向上游隐藏认证信息[​](#向上游隐藏认证信息 "向上游隐藏认证信息的直接链接")

以下示例演示了如何通过配置 `hide_credentials`，防止将客户端凭证（`Authorization` 请求头）发送到上游服务。使用 APISIX 时，包含客户端凭证的 `Authorization` 请求头默认会转发到上游服务，这在某些情况下可能带来安全风险，因此应考虑按本示例更新 `hide_credentials`。

* Admin API
* ADC
* Ingress Controller

创建一个消费者 `johndoe`：

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

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

  -d '{

    "username": "johndoe"

  }'
```

为该消费者创建 `basic-auth` 凭证：

```
curl "http://127.0.0.1:9180/apisix/admin/consumers/johndoe/credentials" -X PUT \

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

  -d '{

    "id": "cred-john-basic-auth",

    "plugins": {

      "basic-auth": {

        "username": "johndoe",

        "password": "john-key"

      }

    }

  }'
```

#### 不隐藏凭证[​](#不隐藏凭证 "不隐藏凭证的直接链接")

创建一个启用 `basic-auth` 的路由，并将 `hide_credentials` 配置为 `false`（这是默认配置）：

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

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

-d '{

  "id": "basic-auth-route",

  "uri": "/anything",

  "plugins": {

    "basic-auth": {

      "hide_credentials": false

    }

  },

  "upstream": {

    "type": "roundrobin",

    "nodes": {

      "httpbin.org:80": 1

    }

  }

}'
```

创建一个配置了 `basic-auth` 凭证的消费者，以及一个配置了 `basic-auth` 插件的路由：

adc.yaml

```
consumers:

  - username: johndoe

    credentials:

      - name: basic-auth

        type: basic-auth

        config:

          username: johndoe

          password: john-key

services:

  - name: basic-auth-service

    routes:

      - name: basic-auth-route

        uris:

          - /anything

        plugins:

          basic-auth:

            hide_credentials: false

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

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

```
adc diff -f adc.yaml \

  --include-resource-type consumer \

  --include-resource-type service \

  --label-selector docs-example=basic-auth
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type consumer \

  --include-resource-type service \

  --label-selector docs-example=basic-auth
```

创建一个配置了 `basic-auth` 凭证的消费者，以及一个配置了 `basic-auth` 插件的路由：

* Gateway API
* APISIX CRD

basic-auth-ic.yaml

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

kind: Consumer

metadata:

  namespace: aic

  name: johndoe

spec:

  gatewayRef:

    name: apisix

  credentials:

    - type: basic-auth

      name: primary-cred

      config:

        username: johndoe

        password: john-key

---

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: basic-auth-plugin-config

spec:

  plugins:

    - name: basic-auth

      config:

        _meta:

          disable: false

        hide_credentials: false

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: basic-auth-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /anything

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: basic-auth-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

将配置应用到集群：

```
kubectl apply -f basic-auth-ic.yaml
```

basic-auth-ic.yaml

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

kind: ApisixConsumer

metadata:

  namespace: aic

  name: johndoe

spec:

  ingressClassName: apisix

  authParameter:

    basicAuth:

      value:

        username: johndoe

        password: john-key

---

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: basic-auth-route

spec:

  ingressClassName: apisix

  http:

    - name: basic-auth-route

      match:

        paths:

          - /anything

      upstreams:

      - name: httpbin-external-domain

      plugins:

      - name: basic-auth

        enable: true

        config:

          hide_credentials: false
```

将配置应用到集群：

```
kubectl apply -f basic-auth-ic.yaml
```

使用有效密钥发送请求：

```
curl -i "http://127.0.0.1:9080/anything" -u johndoe:john-key
```

你应该会看到包含以下内容的 `HTTP/1.1 200 OK` 响应：

```
{

  "args": {}, 

  "data": "", 

  "files": {}, 

  "form": {}, 

  "headers": {

    "Accept": "*/*", 

    "Authorization": "Basic am9obmRvZTpqb2huLWtleQ==",

    "Host": "127.0.0.1",

    "User-Agent": "curl/8.6.0", 

    "X-Amzn-Trace-Id": "Root=1-66cc2195-22bd5f401b13480e63c498c6",

    "X-Consumer-Username": "johndoe",

    "X-Credential-Identifier": "cred-john-basic-auth",

    "X-Forwarded-Host": "127.0.0.1"

  }, 

  "json": null, 

  "method": "GET", 

  "origin": "192.168.65.1, 43.228.226.23", 

  "url": "http://127.0.0.1/anything"

}
```

注意，上游服务可以看到经过 Base64 编码的凭证。

提示

你也可以通过 `Authorization` 请求头传递经过 Base64 编码的凭证，如下所示：

```
curl -i "http://127.0.0.1:9080/anything" -H "Authorization: Basic am9obmRvZTpqb2huLWtleQ=="
```

#### 隐藏凭证[​](#隐藏凭证 "隐藏凭证的直接链接")

* Admin API
* ADC
* Ingress Controller

将插件的 `hide_credentials` 更新为 `true`：

```
curl "http://127.0.0.1:9180/apisix/admin/routes/basic-auth-route" -X PATCH \

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

-d '{

  "plugins": {

    "basic-auth": {

      "hide_credentials": true

    }

  }

}'
```

更新路由配置：

adc.yaml

```
# 其他配置

# ...

services:

  - name: basic-auth-service

    routes:

      - name: basic-auth-route

        uris:

          - /anything

        plugins:

          basic-auth:

            hide_credentials: 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=basic-auth
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=basic-auth
```

* Gateway API
* APISIX CRD

更新 `PluginConfig`，将 `hide_credentials` 设置为 `true`：

basic-auth-ic.yaml

```
# 其他配置

# ---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: basic-auth-plugin-config

spec:

  plugins:

    - name: basic-auth

      config:

        _meta:

          disable: false

        hide_credentials: true
```

将配置应用到集群：

```
kubectl apply -f basic-auth-ic.yaml
```

更新 `ApisixRoute`，将 `hide_credentials` 设置为 `true`：

basic-auth-ic.yaml

```
# 其他配置

# ---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: basic-auth-route

spec:

  ingressClassName: apisix

  http:

    - name: basic-auth-route

      match:

        paths:

          - /anything

      upstreams:

      - name: httpbin-external-domain

      plugins:

      - name: basic-auth

        enable: true

        config:

          hide_credentials: true
```

将配置应用到集群：

```
kubectl apply -f basic-auth-ic.yaml
```

使用有效密钥发送请求：

```
curl -i "http://127.0.0.1:9080/anything" -u johndoe:john-key
```

你应该会看到包含以下内容的 `HTTP/1.1 200 OK` 响应：

```
{

  "args": {}, 

  "data": "", 

  "files": {}, 

  "form": {}, 

  "headers": {

    "Accept": "*/*",

    "Host": "127.0.0.1",

    "User-Agent": "curl/8.6.0",

    "X-Amzn-Trace-Id": "Root=1-66cc21a7-4f6ac87946e25f325167d53a",

    "X-Consumer-Username": "johndoe",

    "X-Credential-Identifier": "cred-john-basic-auth",

    "X-Forwarded-Host": "127.0.0.1"

  }, 

  "json": null,

  "method": "GET",

  "origin": "192.168.65.1, 43.228.226.23",

  "url": "http://127.0.0.1/anything"

}
```

注意，凭证不再对上游服务可见。

### 将消费者自定义 ID 添加到请求头[​](#将消费者自定义-id-添加到请求头 "将消费者自定义 ID 添加到请求头的直接链接")

以下示例展示了如何将消费者自定义 ID 添加到已认证请求的 `Consumer-Custom-Id` 请求头中，以便按需实现额外逻辑。

* Admin API
* ADC
* Ingress Controller

创建一个带有自定义 ID 标签的消费者 `johndoe`：

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

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

  -d '{

    "username": "johndoe",

    "labels": {

      "custom_id": "495aec6a"

    }

  }'
```

为该消费者创建 `basic-auth` 凭证：

```
curl "http://127.0.0.1:9180/apisix/admin/consumers/johndoe/credentials" -X PUT \

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

  -d '{

    "id": "cred-john-basic-auth",

    "plugins": {

      "basic-auth": {

        "username": "johndoe",

        "password": "john-key"

      }

    }

  }'
```

创建一个启用 `basic-auth` 的路由：

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

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

  -d '{

    "id": "basic-auth-route",

    "uri": "/anything",

    "plugins": {

      "basic-auth": {}

    },

    "upstream": {

      "type": "roundrobin",

      "nodes": {

        "httpbin.org:80": 1

      }

    }

  }'
```

创建一个配置了 `basic-auth` 凭证的消费者，以及一个启用了 `basic-auth` 插件的路由：

adc.yaml

```
consumers:

  - username: johndoe

    labels:

      custom_id: "495aec6a"

    credentials:

      - name: basic-auth

        type: basic-auth

        config:

          username: johndoe

          password: john-key

services:

  - name: basic-auth-service

    routes:

      - name: basic-auth-route

        uris:

          - /anything

        plugins:

          basic-auth: {}

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

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

```
adc diff -f adc.yaml \

  --include-resource-type consumer \

  --include-resource-type service \

  --label-selector docs-example=basic-auth
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type consumer \

  --include-resource-type service \

  --label-selector docs-example=basic-auth
```

创建一个配置了 `basic-auth` 凭证的消费者，以及一个启用了 `basic-auth` 插件的路由：

* Gateway API
* APISIX CRD

basic-auth-ic.yaml

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

kind: Consumer

metadata:

  namespace: aic

  name: johndoe

  labels:

    custom_id: "495aec6a"

spec:

  gatewayRef:

    name: apisix

  credentials:

    - type: basic-auth

      name: primary-key

      config:

        username: johndoe

        password: john-key

---

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: basic-auth-plugin-config

spec:

  plugins:

    - name: basic-auth

      config:

        _meta:

          disable: false

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: basic-auth-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /anything

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: basic-auth-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

将配置应用到集群：

```
kubectl apply -f basic-auth-ic.yaml
```

basic-auth-ic.yaml

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

kind: ApisixConsumer

metadata:

  namespace: aic

  name: johndoe

  labels:

    custom_id: "495aec6a"

spec:

  ingressClassName: apisix

  authParameter:

    basicAuth:

      value:

        username: johndoe

        password: john-key

---

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: basic-auth-route

spec:

  ingressClassName: apisix

  http:

    - name: basic-auth-route

      match:

        paths:

          - /anything

      upstreams:

        - name: httpbin-external-domain

      plugins:

        - name: basic-auth

          enable: true

          config:

            _meta:

              disable: false
```

将配置应用到集群：

```
kubectl apply -f basic-auth-ic.yaml
```

要进行验证，请使用有效密钥向路由发送请求：

```
curl -i "http://127.0.0.1:9080/anything" -u johndoe:john-key
```

你应该会看到类似以下的 `HTTP/1.1 200 OK` 响应：

```
{

  "args": {},

  "data": "", 

  "files": {}, 

  "form": {}, 

  "headers": {

    "Accept": "*/*", 

    "Authorization": "Basic am9obmRvZTpqb2huLWtleQ==", 

    "Host": "127.0.0.1",

    "User-Agent": "curl/8.6.0",

    "X-Amzn-Trace-Id": "Root=1-66ea8d64-33df89052ae198a706e18c2a", 

    "X-Consumer-Username": "aic_johndoe",

    "X-Consumer-Custom-Id": "495aec6a",

    "X-Forwarded-Host": "127.0.0.1"

  }, 

  "json": null, 

  "method": "GET", 

  "origin": "192.168.65.1, 205.198.122.37", 

  "url": "http://127.0.0.1/anything"

}
```

如果你想将更多消费者自定义请求头添加到已认证请求中，请参阅 [`attach-consumer-label`](https://docs.apiseven.com/hub/attach-consumer-label.md) 插件。

### 针对匿名消费者的速率限制[​](#针对匿名消费者的速率限制 "针对匿名消费者的速率限制的直接链接")

以下示例展示了如何针对普通消费者和匿名消费者配置不同的速率限制策略，其中匿名消费者无需认证，但配额较少。

* Admin API
* ADC
* Ingress Controller

创建一个普通消费者 `johndoe`，并配置 `limit-count` 插件，允许在 30 秒窗口内有 3 次配额：

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

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

  -d '{

    "username": "johndoe",

    "plugins": {

      "limit-count": {

        "count": 3,

        "time_window": 30,

        "rejected_code": 429,

        "policy": "local"

      }

    }

  }'
```

为消费者 `johndoe` 创建 `basic-auth` 凭证：

```
curl "http://127.0.0.1:9180/apisix/admin/consumers/johndoe/credentials" -X PUT \

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

  -d '{

    "id": "cred-john-basic-auth",

    "plugins": {

      "basic-auth": {

        "username": "johndoe",

        "password": "john-key"

      }

    }

  }'
```

创建一个匿名用户 `anonymous`，并配置 `limit-count` 插件，允许在 30 秒窗口内有 1 次配额：

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

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

  -d '{

    "username": "anonymous",

    "plugins": {

      "limit-count": {

        "count": 1,

        "time_window": 30,

        "rejected_code": 429,

        "policy": "local"

      }

    }

  }'
```

创建一个路由并配置 `basic-auth` 插件，允许匿名消费者 `anonymous` 绕过认证：

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

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

  -d '{

    "id": "basic-auth-route",

    "uri": "/anything",

    "plugins": {

      "basic-auth": {

        "anonymous_consumer": "anonymous"

      }

    },

    "upstream": {

      "type": "roundrobin",

      "nodes": {

        "httpbin.org:80": 1

      }

    }

  }'
```

为消费者配置不同的限流策略，并创建一个接受匿名用户的路由：

adc.yaml

```
consumers:

  - username: johndoe

    plugins:

      limit-count:

        count: 3

        time_window: 30

        rejected_code: 429

        policy: local

    credentials:

      - name: basic-auth

        type: basic-auth

        config:

          username: johndoe

          password: john-key

  - username: anonymous

    plugins:

      limit-count:

        count: 1

        time_window: 30

        rejected_code: 429

        policy: local

services:

  - name: anonymous-rate-limit-service

    routes:

      - name: basic-auth-route

        uris:

          - /anything

        plugins:

          basic-auth:

            anonymous_consumer: anonymous

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

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

```
adc diff -f adc.yaml \

  --include-resource-type consumer \

  --include-resource-type service \

  --label-selector docs-example=basic-auth
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type consumer \

  --include-resource-type service \

  --label-selector docs-example=basic-auth
```

* Gateway API
* APISIX CRD

为消费者配置不同的限流策略，并创建一个接受匿名用户的路由：

basic-auth-ic.yaml

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

kind: Consumer

metadata:

  namespace: aic

  name: johndoe

spec:

  gatewayRef:

    name: apisix

  credentials:

    - type: basic-auth

      name: primary-key

      config:

        username: johndoe

        password: john-key

  plugins:

    - name: limit-count

      config:

        count: 3

        time_window: 30

        rejected_code: 429

        policy: local

---

apiVersion: apisix.apache.org/v1alpha1

kind: Consumer

metadata:

  namespace: aic

  name: anonymous

spec:

  gatewayRef:

    name: apisix

  plugins:

    - name: limit-count

      config:

        count: 1

        time_window: 30

        rejected_code: 429

        policy: local

---

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: basic-auth-plugin-config

spec:

  plugins:

    - name: basic-auth

      config:

        anonymous_consumer: aic_anonymous  # namespace_consumername

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: basic-auth-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /anything

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: basic-auth-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

将配置应用到集群：

```
kubectl apply -f basic-auth-ic.yaml
```

为消费者配置不同的限流策略，并创建一个接受匿名用户的路由：

basic-auth-ic.yaml

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

kind: ApisixConsumer

metadata:

  namespace: aic

  name: johndoe

spec:

  ingressClassName: apisix

  authParameter:

    basicAuth:

      value:

        username: johndoe

        password: john-key

  plugins:

    - name: limit-count

      enable: true

      config:

        count: 3

        time_window: 30

        rejected_code: 429

        policy: local

---

apiVersion: apisix.apache.org/v2

kind: ApisixConsumer

metadata:

  namespace: aic

  name: anonymous

spec:

  ingressClassName: apisix

  plugins:

    - name: limit-count

      enable: true

      config:

        count: 1

        time_window: 30

        rejected_code: 429

        policy: local

---

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: basic-auth-route

spec:

  ingressClassName: apisix

  http:

    - name: basic-auth-route

      match:

        paths:

          - /anything

      upstreams:

        - name: httpbin-external-domain

      plugins:

        - name: basic-auth

          enable: true

          config:

            anonymous_consumer: aic_anonymous
```

将配置应用到集群：

```
kubectl apply -f basic-auth-ic.yaml
```

要进行验证，请使用 `johndoe` 的凭证连续发送 5 个请求：

```
resp=$(seq 5 | xargs -I{} curl "http://127.0.0.1:9080/anything" -u johndoe:john-key -o /dev/null -s -w "%{http_code}\n") && \

  count_200=$(echo "$resp" | grep "200" | wc -l) && \

  count_429=$(echo "$resp" | grep "429" | wc -l) && \

  echo "200": $count_200, "429": $count_429
```

你应该会看到以下响应，显示在 5 个请求中，有 3 个请求成功（状态码 `200`），而其他请求被拒绝（状态码 `429`）。

```
200:    3, 429:    2
```

发送 5 个匿名请求：

```
resp=$(seq 5 | xargs -I{} curl "http://127.0.0.1:9080/anything" -o /dev/null -s -w "%{http_code}\n") && \

  count_200=$(echo "$resp" | grep "200" | wc -l) && \

  count_429=$(echo "$resp" | grep "429" | wc -l) && \

  echo "200": $count_200, "429": $count_429
```

你应该会看到以下响应，显示只有一个请求成功：

```
200:    1, 429:    4
```
