# 密钥认证

API 网关的主要作用是连接 API 消费者和提供者。出于安全原因，在允许消费者访问上游资源之前，它应该对消费者进行身份认证和授权。

![Key Authentication](https://static.api7.ai/uploads/2023/02/08/8mRaK3v1_consumer.png)

APISIX 具有灵活的插件扩展系统，并拥有许多用于用户身份认证和授权的现有插件。例如：

* [Key Authentication](https://docs.apiseven.com/hub/key-auth.md)
* [Basic Authentication](https://docs.apiseven.com/hub/basic-auth.md)
* [HMAC](https://docs.apiseven.com/hub/hmac-auth.md)
* [JSON Web Token (JWT) Authentication](https://docs.apiseven.com/hub/jwt-auth.md)
* [OpenID Connect](https://docs.apiseven.com/hub/openid-connect.md)
* [Keycloak Authorization](https://docs.apiseven.com/hub/authz-keycloak.md)
* [Casdoor Authorization](https://apisix.apache.org/docs/apisix/plugins/authz-casdoor/)
* [Casbin Authorization](https://apisix.apache.org/docs/apisix/plugins/authz-casbin/)
* [Open Policy Agent (OPA)](https://docs.apiseven.com/hub/opa.md)
* [Wolf RBAC](https://apisix.apache.org/docs/apisix/plugins/wolf-rbac/)
* [Central Authentication Service (CAS)](https://apisix.apache.org/docs/apisix/plugins/cas-auth/)
* [LDAP](https://apisix.apache.org/docs/apisix/plugins/ldap-auth/)
* [Forward Authentication](https://docs.apiseven.com/hub/forward-auth.md)

在本教程中，你将创建一个[消费者](https://docs.apiseven.com/apisix/key-concepts/consumers.md)，使用[密钥认证](https://docs.apiseven.com/hub/key-auth.md)配置其[凭证](https://docs.apiseven.com/apisix/key-concepts/consumers.md)，并学习如何启用和禁用密钥认证。

## 关键概念[​](#关键概念 "关键概念的直接链接")

### 消费者[​](#消费者 "消费者的直接链接")

*消费者* 是指使用 API 的应用程序或开发者。

在 APISIX 中，消费者需要唯一的 `username`。使用密钥认证时，应创建一个 `plugins` 对象包含 `key-auth` 的凭证，并在受保护路由或服务的 `plugins` 对象中启用 `key-auth`。

### 密钥认证[​](#密钥认证 "密钥认证的直接链接")

密钥认证是一种相对简单但广泛使用的身份认证方法。其思路如下：

1. 管理员将身份认证插件添加到路由。
2. API 消费者在发送请求时，将密钥附加到查询字符串或请求头中以进行身份认证。

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

1. 完成 [安装 APISIX](https://docs.apiseven.com/apisix/getting-started.md) 以在 Docker 中安装 APISIX。
2. 完成 [配置路由](https://docs.apiseven.com/apisix/getting-started/configure-routes.md)。
3. 如果使用这些工具，请安装 [ADC](https://docs.apiseven.com/apisix/reference/adc.md) 或 [APISIX-MCP](https://docs.apiseven.com/apisix/reference/apisix-mcp.md)。

## 配置密钥认证[​](#配置密钥认证 "配置密钥认证的直接链接")

* Admin API
* ADC
* APISIX-MCP

### 创建消费者

创建消费者 `tom`：

警告

请在生产环境中使用复杂的密钥。

```
curl -i "http://127.0.0.1:9180/apisix/admin/consumers" -X PUT -d '

{

  "username": "tom"

}'
```

如果消费者创建成功，你将收到 `HTTP/1.1 201 Created` 响应。

### 配置消费者凭证

为 `tom` 配置 `key-auth` 凭证：

```
curl "http://127.0.0.1:9180/apisix/admin/consumers/tom/credentials" -X PUT -d '

{

  "id": "cred-tom-key-auth",

  "plugins": {

    "key-auth": {

      "key": "secret-key"

    }

  }

}'
```

如果消费者凭证创建成功，你将收到 `HTTP/1.1 201 Created` 响应。

### 启用身份认证

更新 [配置路由](https://docs.apiseven.com/apisix/getting-started/configure-routes.md) 中的 `getting-started-ip` 路由以添加 `key-auth` 插件：

```
curl -i "http://127.0.0.1:9180/apisix/admin/routes/getting-started-ip" -X PATCH -d '

{

  "plugins": {

    "key-auth": {}

  }

}'
```

如果路由更新成功，你将收到 `HTTP/1.1 200 OK` 响应。

创建一个包含消费者和路由的 ADC 配置文件：

adc.yaml

```
consumers:

  - username: tom

    credentials:

      - name: tom-key

        type: key-auth

        config:

          key: secret-key

services:

  - name: httpbin Service

    routes:

      - uris:

          - /ip

        name: getting-started-ip

        plugins:

          key-auth: {}

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览服务和消费者变更。以下选项仅比较本教程的服务和消费者，因此其他网关资源不会受到影响：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --include-resource-type consumer \

  --label-selector docs-example=getting-started-ip
```

检查 `diff.yaml`，确认其中仅包含预期的服务、路由、消费者和凭据变更。然后使用相同范围同步已审查的配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --include-resource-type consumer \

  --label-selector docs-example=getting-started-ip
```

在你的 AI 客户端中输入以下提示：

```
Create a consumer named tom in APISIX and the key-auth credential for the consumer should be secret-key.

Enable the key-auth plugin on the route getting-started-ip, requiring consumers to provide an API key when accessing that route.
```

你应该看到类似的响应：

```
Created consumer 'tom' with key-auth credential and enabled key-auth plugin on route 'getting-started-ip'. The consumer can now access the route using API key 'secret-key' in either the 'apikey' header or query parameter.
```

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

你将在本节中验证密钥认证是否已成功启用。

* Admin API
* ADC
* APISIX-MCP

### 发送不带 Key 的请求

发送不带 `apikey` 头的请求。

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

由于未提供密钥，你将收到未授权的 `HTTP/1.1 401 Unauthorized` 响应。

### 发送携带错误 Key 的请求

发送在 `apikey` 头中带有错误密钥的请求。

```
curl -i "http://127.0.0.1:9080/ip" -H 'apikey: wrong-key'
```

由于密钥不正确，你将收到 `HTTP/1.1 401 Unauthorized` 响应。

### 发送携带正确 Key 的请求

发送在 `apikey` 头中带有正确密钥的请求。

```
curl -i "http://127.0.0.1:9080/ip" -H 'apikey: secret-key'
```

由于提供了正确的密钥，你将收到 `HTTP/1.1 200 OK` 响应。

### 发送不带 Key 的请求

发送不带 `apikey` 头的请求。

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

由于未提供密钥，你将收到未授权的 `HTTP/1.1 401 Unauthorized` 响应。

### 发送携带错误 Key 的请求

发送在 `apikey` 头中带有错误密钥的请求。

```
curl -i "http://127.0.0.1:9080/ip" -H 'apikey: wrong-key'
```

由于密钥不正确，你将收到 `HTTP/1.1 401 Unauthorized` 响应。

### 发送携带正确 Key 的请求

发送在 `apikey` 头中带有正确密钥的请求。

```
curl -i "http://127.0.0.1:9080/ip" -H 'apikey: secret-key'
```

由于提供了正确的密钥，你将收到 `HTTP/1.1 200 OK` 响应。

### 发送不带 Key 的请求

在你的 AI 客户端中输入以下提示：

```
Send a request to the route without any authentication header.
```

你应该看到类似的响应：

```
Unauthenticated request to '/ip' returned 401 as expected
```

### 发送携带错误 Key 的请求

在你的 AI 客户端中输入以下提示：

```
Send a request to the route with wrong-key.
```

你应该看到类似的响应：

```
Invalid API key returns 401 (wrong credentials)
```

### 发送携带正确 Key 的请求

在你的 AI 客户端中输入以下提示：

```
Send a request to the route with secret-key.
```

你应该看到类似的响应：

```
Valid API key 'secret-key' authenticates successfully (200)
```

## 禁用身份认证[​](#禁用身份认证 "禁用身份认证的直接链接")

通过将 `_meta.disable` 参数设置为 `true` 来禁用密钥认证插件。

* Admin API
* ADC
* APISIX-MCP

```
curl "http://127.0.0.1:9180/apisix/admin/routes/getting-started-ip" -X PATCH -d '

{

  "plugins": {

    "key-auth": {

      "_meta": {

        "disable": true

      }

    }

  }

}'
```

发送不带任何密钥的请求以进行验证：

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

由于密钥认证已禁用，你将收到 `HTTP/1.1 200 OK` 响应。

adc.yaml

```
consumers:

  - username: tom

    credentials:

      - name: tom-key

        type: key-auth

        config:

          key: secret-key

services:

  - name: httpbin Service

    routes:

      - uris:

          - /ip

        name: getting-started-ip

        plugins:

          key-auth:

            _meta:

              disable: true

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览服务和消费者变更：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --include-resource-type consumer \

  --label-selector docs-example=getting-started-ip
```

检查 `diff.yaml`，确认其中仅包含预期的更新。然后使用相同范围同步已审查的配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --include-resource-type consumer \

  --label-selector docs-example=getting-started-ip
```

发送不带任何密钥的请求以进行验证：

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

由于密钥认证已禁用，你将收到 `HTTP/1.1 200 OK` 响应。

在你的 AI 客户端中输入以下提示：

```
Disable the key authentication plugin for the route getting-started-ip while keeping its configuration intact.
```

你应该看到类似的响应：

```
Successfully disabled the key-auth plugin for route 'getting-started-ip' while maintaining all other configuration. The route now:



* Still matches requests to URI '/ip'

* Forwards to upstream httpbin.org:80

* No longer requires API key authentication

Retains all other settings including load balancing configuration
```

在你的 AI 客户端中发送不带任何密钥的请求：

```
Send a request to the route without any key.
```

你应该看到类似的响应：

```
The request to the /ip route without an API key was successful (HTTP 200).
```

## 下一步[​](#下一步 "下一步的直接链接")

你已经学习了如何为路由配置密钥认证。在下一个教程中，你将学习如何配置限流限速。
