# 配置 HMAC 身份认证

HMAC 身份认证要求客户端使用共享密钥为请求签名。签名涵盖已配置的请求目标和签名请求头。签名包含时间戳时，`clock_skew` 会限制可接受请求的时间范围，但无法阻止在该时间范围内重放同一个有效请求。

API7 网关的 [`hmac-auth`](https://docs.apiseven.com/hub/hmac-auth.md) 插件会根据所配置的消费者凭证验证传入签名。

本指南介绍常见签名工作流。有关完整插件字段参考以及签名请求头、请求体校验等高级选项，请参阅 [`hmac-auth`](https://docs.apiseven.com/hub/hmac-auth.md)。

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

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

## 配置 HMAC 身份认证[​](#配置-hmac-身份认证 "配置 HMAC 身份认证的直接链接")

配置 HMAC 身份认证包含三个步骤：

1. 创建具有有效上游的服务。
2. 创建启用 `hmac-auth` 的路由。
3. 创建消费者并挂载 HMAC 凭证。

### 第 1 步：创建具有上游的服务[​](#第-1-步创建具有上游的服务 "第 1 步：创建具有上游的服务的直接链接")

* Admin API
* ADC

```
curl -k "https://localhost:7443/apisix/admin/services/hmac-auth-httpbin-service?gateway_group_id={gateway_group_id}" -X PUT \

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

  -H "Content-Type: application/json" \

  -d '{

    "name": "hmac-auth-httpbin-service",

    "upstream": {

      "type": "roundrobin",

      "scheme": "http",

      "nodes": [

        {

          "host": "httpbin.org",

          "port": 80,

          "weight": 100

        }

      ]

    }

  }'
```

adc.yaml

```
services:

  - name: hmac-auth-httpbin-service

    upstream:

      name: default

      scheme: http

      nodes:

        - host: httpbin.org

          port: 80

          weight: 100

    routes:

      - name: hmac-auth-route

        uris:

          - /anything/hmac-auth

        methods:

          - GET

        plugins:

          hmac-auth:

            clock_skew: 300

            allowed_algorithms:

              - hmac-sha256

    labels:

      docs-example: hmac-auth-httpbin-service

consumers:

  - username: hmac-auth-consumer

    credentials:

      - name: hmac-auth-consumer-cred

        type: hmac-auth

        config:

          key_id: client-1

          secret_key: my-hmac-secret

    labels:

      docs-example: hmac-auth-httpbin-service
```

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

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --include-resource-type consumer \

  --label-selector docs-example=hmac-auth-httpbin-service
```

审查变更后同步配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --include-resource-type consumer \

  --label-selector docs-example=hmac-auth-httpbin-service
```

### 第 2 步：创建路由并启用 `hmac-auth`[​](#第-2-步创建路由并启用-hmac-auth "第-2-步创建路由并启用-hmac-auth的直接链接")

* Admin API
* ADC

```
curl -k "https://localhost:7443/apisix/admin/routes/hmac-auth-route?gateway_group_id={gateway_group_id}" -X PUT \

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

  -H "Content-Type: application/json" \

  -d '{

    "name": "hmac-auth-route",

    "paths": ["/anything/hmac-auth"],

    "methods": ["GET"],

    "service_id": "hmac-auth-httpbin-service",

    "plugins": {

      "hmac-auth": {

        "clock_skew": 300,

        "allowed_algorithms": ["hmac-sha256"]

      }

    }

  }'
```

路由已包含在上一个 `adc.yaml` 示例中。

### 第 3 步：创建消费者和凭证[​](#第-3-步创建消费者和凭证 "第 3 步：创建消费者和凭证的直接链接")

* Admin API
* ADC

```
# 1. 创建消费者

curl -k "https://localhost:7443/apisix/admin/consumers/hmac-auth-consumer?gateway_group_id={gateway_group_id}" -X PUT \

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

  -H "Content-Type: application/json" \

  -d '{

    "username": "hmac-auth-consumer"

  }'



# 2. 创建 hmac-auth 凭证

curl -k "https://localhost:7443/apisix/admin/consumers/hmac-auth-consumer/credentials/hmac-auth-consumer-cred?gateway_group_id={gateway_group_id}" -X PUT \

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

  -H "Content-Type: application/json" \

  -d '{

    "name": "hmac-auth-consumer-cred",

    "plugins": {

      "hmac-auth": {

        "key_id": "client-1",

        "secret_key": "my-hmac-secret"

      }

    }

  }'
```

消费者和凭证已包含在上一个 `adc.yaml` 示例中。

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

首先发送不含 HMAC 请求头的请求。网关应返回 `401 Unauthorized`：

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

然后使用 Python 生成并发送签名请求：

hmac-request.py

```
import base64

import hashlib

import hmac

import urllib.request

from email.utils import formatdate



key_id = "client-1"

secret_key = b"my-hmac-secret"

request_path = "/anything/hmac-auth"

date_header = formatdate(timeval=None, localtime=False, usegmt=True)



signing_string = f"{key_id}\nGET {request_path}\ndate: {date_header}\n"

signature = base64.b64encode(

    hmac.new(secret_key, signing_string.encode(), hashlib.sha256).digest()

).decode()



request = urllib.request.Request(

    "http://127.0.0.1:9080/anything/hmac-auth",

    headers={

        "Date": date_header,

        "Authorization": (

            f'Signature keyId="{key_id}",algorithm="hmac-sha256",'

            f'headers="@request-target date",signature="{signature}"'

        ),

    },

)



with urllib.request.urlopen(request, timeout=20) as response:

    print(response.status)

    print(response.read().decode())
```

运行脚本：

```
python3 hmac-request.py
```

应收到 `200 OK`，上游响应应包含类似以下的请求头：

```
{

  "headers": {

    "Authorization": "Signature keyId=\"client-1\",algorithm=\"hmac-sha256\",headers=\"@request-target date\",signature=\"<signature>\"",

    "Date": "Tue, 21 Apr 2026 09:06:44 GMT",

    "X-Consumer-Username": "hmac-auth-consumer",

    "X-Credential-Identifier": "hmac-auth-consumer-cred"

  }

}
```

如果应用配置后，已认证请求仍返回 `401` 或路由返回 `404`，请等待几秒，让最新配置下发到网关后重试。

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

* [配置 JWT 身份认证](https://docs.apiseven.com/api7-gateway/how-to-guides/api-security/jwt-auth.md)——使用 JSON Web Token 实现无状态身份认证。
* [配置 Key 身份认证](https://docs.apiseven.com/api7-gateway/how-to-guides/api-security/key-auth.md)——使用简单 API Key（API 密钥）快速保护 API。
* [消费者和凭证](https://docs.apiseven.com/api7-gateway/key-concepts/consumers-and-credentials.md)——理解 API7 网关如何管理身份。
