This is an automated email from the ASF dual-hosted git repository.

wenming pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/apisix.git


The following commit(s) were added to refs/heads/master by this push:
     new 3f6de4ad4 docs: improve `hmac-auth` plugin docs and update docs for 
anonymous consumer  (#11867)
3f6de4ad4 is described below

commit 3f6de4ad48dc806149e08652ee36b1c1554a8001
Author: Traky Deng <[email protected]>
AuthorDate: Tue Apr 8 14:58:17 2025 +0800

    docs: improve `hmac-auth` plugin docs and update docs for anonymous 
consumer  (#11867)
---
 docs/en/latest/plugins/hmac-auth.md | 289 ++++++++++++++++++++++----
 docs/zh/latest/plugins/hmac-auth.md | 391 +++++++++++++++++++++++++++---------
 2 files changed, 547 insertions(+), 133 deletions(-)

diff --git a/docs/en/latest/plugins/hmac-auth.md 
b/docs/en/latest/plugins/hmac-auth.md
index 5ba08c05b..354af2a15 100644
--- a/docs/en/latest/plugins/hmac-auth.md
+++ b/docs/en/latest/plugins/hmac-auth.md
@@ -6,7 +6,7 @@ keywords:
   - Plugin
   - HMAC Authentication
   - hmac-auth
-description: This document contains information about the Apache APISIX 
hmac-auth Plugin.
+description: The hmac-auth Plugin supports HMAC authentication to ensure 
request integrity, preventing modifications during transmission and enhancing 
API security.
 ---
 
 <!--
@@ -30,11 +30,13 @@ description: This document contains information about the 
Apache APISIX hmac-aut
 
 ## Description
 
-The `hmac-auth` plugin supports HMAC (Hash-based Message Authentication Code) 
authentication as a mechanism to ensure the integrity of requests, preventing 
them from being modified during transmissions. To use the plugin, you would 
configure HMAC secret keys on [Consumers](../terminology/consumer.md) and 
enable the plugin on Routes or Services.
+The `hmac-auth` Plugin supports HMAC (Hash-based Message Authentication Code) 
authentication as a mechanism to ensure the integrity of requests, preventing 
them from being modified during transmissions. To use the Plugin, you would 
configure HMAC secret keys on [Consumers](../terminology/consumer.md) and 
enable the Plugin on Routes or Services.
 
-Once enabled, the plugin verifies the HMAC signature in the request's 
`Authorization` header and check that incoming requests are from trusted 
sources. Specifically, when APISIX receives an HMAC-signed request, the key ID 
is extracted from the `Authorization` header. APISIX then retrieves the 
corresponding consumer configuration, including the secret key. If the key ID 
is valid and exists, APISIX generates an HMAC signature using the request's 
`Date` header and the secret key. If this ge [...]
+When a Consumer is successfully authenticated, APISIX adds additional headers, 
such as `X-Consumer-Username`, `X-Credential-Indentifier`, and other Consumer 
custom headers if configured, to the request, before proxying it to the 
Upstream service. The Upstream service will be able to differentiate between 
consumers and implement additional logics as needed. If any of these values is 
not available, the corresponding header will not be added.
 
-The plugin implementation is based on 
[draft-cavage-http-signatures](https://www.ietf.org/archive/id/draft-cavage-http-signatures-12.txt).
+Once enabled, the Plugin verifies the HMAC signature in the request's 
`Authorization` header and check that incoming requests are from trusted 
sources. Specifically, when APISIX receives an HMAC-signed request, the key ID 
is extracted from the `Authorization` header. APISIX then retrieves the 
corresponding Consumer configuration, including the secret key. If the key ID 
is valid and exists, APISIX generates an HMAC signature using the request's 
`Date` header and the secret key. If this ge [...]
+
+The Plugin implementation is based on 
[draft-cavage-http-signatures](https://www.ietf.org/archive/id/draft-cavage-http-signatures-12.txt).
 
 ## Attributes
 
@@ -42,23 +44,26 @@ The following attributes are available for configurations 
on Consumers or Creden
 
 | Name                  | Type          | Required | Default       | Valid 
values                                | Description                             
                                                                                
                                                                                
  |
 
|-----------------------|---------------|----------|---------------|---------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| key_id            | string        | True     |               |               
                              | Unique identifier for the consumer, which 
identifies the associated configurations such as the secret key.                
                                                                              |
+| key_id            | string        | True     |               |               
                              | Unique identifier for the Consumer, which 
identifies the associated configurations such as the secret key.                
                                                                              |
 | secret_key            | string        | True     |               |           
                                  | Secret key used to generate an HMAC. This 
field supports saving the value in Secret Manager using the [APISIX 
Secret](../terminology/secret.md) resource.                                     
        |
 
 The following attributes are available for configurations on Routes or 
Services.
 
 | Name                  | Type          | Required | Default       | Valid 
values                                | Description                             
                                                                                
                                                                                
  |
 
|-----------------------|---------------|----------|---------------|---------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| allowed_algorithms             | array[string]        | False    | 
["hmac-sha1", "hmac-sha256", "hmac-sha512"] | combination of "hmac-sha1", 
"hmac-sha256", and "hmac-sha512" | The list of HMAC algorithms allowed.         
                                                                                
                                                                                
       |
+| allowed_algorithms             | array[string]        | False    | 
["hmac-sha1","hmac-sha256","hmac-sha512"] | combination of 
"hmac-sha1","hmac-sha256",and "hmac-sha512" | The list of HMAC algorithms 
allowed.                                                                        
                                                                                
                        |
 | clock_skew            | integer       | False    | 300             |         
        >=1                          | Maximum allowable time difference in 
seconds between the client request's timestamp and APISIX server's current 
time. This helps account for discrepancies in time synchronization between the 
client’s and server’s clocks and protect against replay attacks. The timestamp 
in the Date header (must be in GMT format) will be used for the calculation.    
    |
 | signed_headers        | array[string] | False    |               |           
                                  | The list of HMAC-signed headers that should 
be included in the client request's HMAC signature.  |
-| validate_request_body | boolean       | False    | false         |           
                   | If true, validate the integrity of the request body to 
ensure it has not been tampered with during transmission. Specifically, the 
plugin creates a SHA-256 base64-encoded digest and compare it to the `Digest` 
header. If the Digest` header is missing or if the digests do not match, the 
validation fails.                          |
-| hide_credentials | boolean       | False    | false         |                
              | If true, do not pass the authorization request header to 
upstream services.                        |
+| validate_request_body | boolean       | False    | false         |           
                   | If true, validate the integrity of the request body to 
ensure it has not been tampered with during transmission. Specifically, the 
Plugin creates a SHA-256 base64-encoded digest and compare it to the `Digest` 
header. If the Digest` header is missing or if the digests do not match, the 
validation fails.                          |
+| hide_credentials | boolean       | False    | false         |                
              | If true, do not pass the authorization request header to 
Upstream services.                        |
+| anonymous_consumer | string    | False    |          |                       
       | Anonymous Consumer name. If configured, allow anonymous users to 
bypass the authentication.                        |
 
 NOTE: `encrypt_fields = {"secret_key"}` is also defined in the schema, which 
means that the field will be stored encrypted in etcd. See [encrypted storage 
fields](../plugin-develop.md#encrypted-storage-fields).
 
 ## Examples
 
+The examples below demonstrate how you can work with the `hmac-auth` Plugin 
for different scenarios.
+
 :::note
 
 You can fetch the `admin_key` from `config.yaml` and save to an environment 
variable with the following command:
@@ -69,20 +74,24 @@ admin_key=$(yq '.deployment.admin.admin_key[0].key' 
conf/config.yaml | sed 's/"/
 
 :::
 
-Before proceeding, create a sample consumer and configure its credential, 
which will be used for all examples below.
+### Implement HMAC Authentication on a Route
+
+The following example demonstrates how to implement HMAC authentications on a 
route. You will also attach a Consumer custom ID to authenticated request in 
the `Consumer-Custom-Id` header, which can be used to implement additional 
logics as needed.
 
-Create a consumer `john`:
+Create a Consumer `john` with a custom ID label:
 
 ```shell
 curl "http://127.0.0.1:9180/apisix/admin/consumers"; -X PUT \
   -H "X-API-KEY: ${admin_key}" \
   -d '{
-    "username": "john"
+    "username": "john",
+    "labels": {
+      "custom_id": "495aec6a"
     }
   }'
 ```
 
-Create `hmac-auth` credential for `john`:
+Create `hmac-auth` Credential for the Consumer:
 
 ```shell
 curl "http://127.0.0.1:9180/apisix/admin/consumers/john/credentials"; -X PUT \
@@ -98,11 +107,7 @@ curl 
"http://127.0.0.1:9180/apisix/admin/consumers/john/credentials"; -X PUT \
   }'
 ```
 
-### Implement HMAC Authentication on a Route
-
-The following example shows how to implement HMAC authentications on a route 
using the most minimal configurations.
-
-Create a route with the `hmac-auth` plugin using its default configurations:
+Create a Route with the `hmac-auth` Plugin using its default configurations:
 
 ```shell
 curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
@@ -134,7 +139,7 @@ from datetime import datetime, timezone
 key_id = "john-key"                # key id
 secret_key = b"john-secret-key"    # secret key
 request_method = "GET"             # HTTP method
-request_path = "/get"              # route URI
+request_path = "/get"              # Route URI
 algorithm= "hmac-sha256"           # can use other algorithms in 
allowed_algorithms
 
 # get current datetime in GMT
@@ -205,6 +210,7 @@ You should see an `HTTP/1.1 200 OK` response similar to the 
following:
     "X-Amzn-Trace-Id": "Root=1-66d96513-2e52d4f35c9b6a2772d667ea",
     "X-Consumer-Username": "john",
     "X-Credential-Identifier": "cred-john-hmac-auth",
+    "X-Consumer-Custom-Id": "495aec6a",
     "X-Forwarded-Host": "127.0.0.1"
   },
   "origin": "192.168.65.1, 34.0.34.160",
@@ -214,11 +220,11 @@ You should see an `HTTP/1.1 200 OK` response similar to 
the following:
 
 ### Hide Authorization Information From Upstream
 
-As seen the in the [last example](#implement-hmac-authentication-on-a-route), 
the `Authorization` header passed to the upstream includes the signature and 
all other details. This could potentially introduce security risks.
+As seen the in the [last example](#implement-hmac-authentication-on-a-route), 
the `Authorization` header passed to the Upstream includes the signature and 
all other details. This could potentially introduce security risks.
 
-The following example shows how to prevent these information from being sent 
to the upstream service.
+The following example demonstrates how to prevent these information from being 
sent to the Upstream service.
 
-Update the plugin configuration to set `hide_credentials` to `true`:
+Update the Plugin configuration to set `hide_credentials` to `true`:
 
 ```shell
 curl "http://127.0.0.1:9180/apisix/admin/routes/hmac-auth-route"; -X PATCH \
@@ -261,9 +267,35 @@ You should see an `HTTP/1.1 200 OK` response and notice 
the `Authorization` head
 
 ### Enable Body Validation
 
-The following example shows how to enable body validation to ensure the 
integrity of the request body.
+The following example demonstrates how to enable body validation to ensure the 
integrity of the request body.
+
+Create a Consumer `john`:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/consumers"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "username": "john"
+  }'
+```
 
-Create a route with the `hmac-auth` plugin as such:
+Create `hmac-auth` Credential for the Consumer:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/consumers/john/credentials"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "cred-john-hmac-auth",
+    "plugins": {
+      "hmac-auth": {
+        "key_id": "john-key",
+        "secret_key": "john-secret-key"
+      }
+    }
+  }'
+```
+
+Create a Route with the `hmac-auth` Plugin as such:
 
 ```shell
 curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
@@ -294,10 +326,10 @@ import hashlib
 import base64
 from datetime import datetime, timezone
 
-key_id = "john-key"                # key id
-secret_key = b"john-secret-key"    # secret key
+key_id = "john-key"                 # key id
+secret_key = b"john-secret-key"     # secret key
 request_method = "POST"             # HTTP method
-request_path = "/post"              # route URI
+request_path = "/post"              # Route URI
 algorithm= "hmac-sha256"            # can use other algorithms in 
allowed_algorithms
 body = '{"name": "world"}'          # example request body
 
@@ -410,9 +442,35 @@ You should see an `HTTP/1.1 401 Unauthorized` response 
with the following messag
 
 ### Mandate Signed Headers
 
-The following example shows how you can mandate certain headers to be signed 
in the request's HMAC signature.
+The following example demonstrates how you can mandate certain headers to be 
signed in the request's HMAC signature.
+
+Create a Consumer `john`:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/consumers"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "username": "john"
+  }'
+```
+
+Create `hmac-auth` Credential for the Consumer:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/consumers/john/credentials"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "cred-john-hmac-auth",
+    "plugins": {
+      "hmac-auth": {
+        "key_id": "john-key",
+        "secret_key": "john-secret-key"
+      }
+    }
+  }'
+```
 
-Create a route with the `hmac-auth` plugin which requires three headers to be 
present in the HMAC signature:
+Create a Route with the `hmac-auth` Plugin which requires three headers to be 
present in the HMAC signature:
 
 ```shell
 curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
@@ -423,7 +481,7 @@ curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
     "methods": ["GET"],
     "plugins": {
       "hmac-auth": {
-        "signed_headers": ["date","x-custom-header-a", "x-custom-header-b"]
+        "signed_headers": ["date","x-custom-header-a","x-custom-header-b"]
       }
     },
     "upstream": {
@@ -446,7 +504,7 @@ from datetime import datetime, timezone
 key_id = "john-key"                # key id
 secret_key = b"john-secret-key"    # secret key
 request_method = "GET"             # HTTP method
-request_path = "/get"              # route URI
+request_path = "/get"              # Route URI
 algorithm= "hmac-sha256"           # can use other algorithms in 
allowed_algorithms
 custom_header_a = "hello123"       # required custom header
 custom_header_b = "world456"       # required custom header
@@ -534,20 +592,169 @@ You should see an `HTTP/1.1 200 OK` response similar to 
the following:
 }
 ```
 
-## Delete Plugin
+### Rate Limit with Anonymous Consumer
+
+The following example demonstrates how you can configure different rate 
limiting policies by regular and anonymous consumers, where the anonymous 
Consumer does not need to authenticate and has less quotas.
 
-To remove the `hmac-auth` Plugin on the Route, you can delete the 
corresponding JSON configuration from the Plugin configuration. APISIX will 
automatically reload and you do not have to restart for this to take effect.
+Create a regular Consumer `john` and configure the `limit-count` Plugin to 
allow for a quota of 3 within a 30-second window:
 
 ```shell
-curl http://127.0.0.1:9180/apisix/admin/routes/1 -H "X-API-KEY: $admin_key" -X 
PUT -d '
-{
-    "uri": "/index.html",
-    "plugins": {},
+curl "http://127.0.0.1:9180/apisix/admin/consumers"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "username": "john",
+    "plugins": {
+      "limit-count": {
+        "count": 3,
+        "time_window": 30,
+        "rejected_code": 429
+      }
+    }
+  }'
+```
+
+Create the `hmac-auth` Credential for the Consumer `john`:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/consumers/john/credentials"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "cred-john-hmac-auth",
+    "plugins": {
+      "hmac-auth": {
+        "key_id": "john-key",
+        "secret_key": "john-secret-key"
+      }
+    }
+  }'
+```
+
+Create an anonymous user `anonymous` and configure the `limit-count` Plugin to 
allow for a quota of 1 within a 30-second window:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/consumers"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "username": "anonymous",
+    "plugins": {
+      "limit-count": {
+        "count": 1,
+        "time_window": 30,
+        "rejected_code": 429
+      }
+    }
+  }'
+```
+
+Create a Route and configure the `hmac-auth` Plugin to accept anonymous 
Consumer `anonymous` from bypassing the authentication:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "hmac-auth-route",
+    "uri": "/get",
+    "methods": ["GET"],
+    "plugins": {
+      "hmac-auth": {
+        "anonymous_consumer": "anonymous"
+      }
+    },
     "upstream": {
-        "type": "roundrobin",
-        "nodes": {
-            "127.0.0.1:1980": 1
-        }
+      "type": "roundrobin",
+      "nodes": {
+        "httpbin.org:80": 1
+      }
     }
-}'
+  }'
+```
+
+Generate a signature. You can use the below Python snippet or other stack of 
your choice:
+
+```python title="hmac-sig-header-gen.py"
+import hmac
+import hashlib
+import base64
+from datetime import datetime, timezone
+
+key_id = "john-key"                # key id
+secret_key = b"john-secret-key"    # secret key
+request_method = "GET"             # HTTP method
+request_path = "/get"              # Route URI
+algorithm= "hmac-sha256"           # can use other algorithms in 
allowed_algorithms
+
+# get current datetime in GMT
+# note: the signature will become invalid after the clock skew (default 300s)
+# you can regenerate the signature after it becomes invalid, or increase the 
clock
+# skew to prolong the validity within the advised security boundary
+gmt_time = datetime.now(timezone.utc).strftime('%a, %d %b %Y %H:%M:%S GMT')
+
+# construct the signing string (ordered)
+# the date and any subsequent custom headers should be lowercased and 
separated by a
+# single space character, i.e. `<key>:<space><value>`
+# 
https://datatracker.ietf.org/doc/html/draft-cavage-http-signatures-12#section-2.1.6
+signing_string = (
+  f"{key_id}\n"
+  f"{request_method} {request_path}\n"
+  f"date: {gmt_time}\n"
+)
+
+# create signature
+signature = hmac.new(secret_key, signing_string.encode('utf-8'), 
hashlib.sha256).digest()
+signature_base64 = base64.b64encode(signature).decode('utf-8')
+
+# construct the request headers
+headers = {
+  "Date": gmt_time,
+  "Authorization": (
+    f'Signature keyId="{key_id}",algorithm="{algorithm}",'
+    f'headers="@request-target date",'
+    f'signature="{signature_base64}"'
+  )
+}
+
+# print headers
+print(headers)
+```
+
+Run the script:
+
+```shell
+python3 hmac-sig-header-gen.py
+```
+
+You should see the request headers printed:
+
+```text
+{'Date': 'Mon, 21 Oct 2024 17:31:18 GMT', 'Authorization': 'Signature 
keyId="john-key",algorithm="hmac-sha256",headers="@request-target 
date",signature="ztFfl9w7LmCrIuPjRC/DWSF4gN6Bt8dBBz4y+u1pzt8="'}
+```
+
+To verify, send five consecutive requests with the generated headers:
+
+```shell
+resp=$(seq 5 | xargs -I{} curl "http://127.0.0.1:9080/anything"; -H "Date: Mon, 
21 Oct 2024 17:31:18 GMT" -H 'Authorization: Signature 
keyId="john-key",algorithm="hmac-sha256",headers="@request-target 
date",signature="ztFfl9w7LmCrIuPjRC/DWSF4gN6Bt8dBBz4y+u1pzt8="' -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
+```
+
+You should see the following response, showing that out of the 5 requests, 3 
requests were successful (status code 200) while the others were rejected 
(status code 429).
+
+```text
+200:    3, 429:    2
+```
+
+Send five anonymous requests:
+
+```shell
+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
+```
+
+You should see the following response, showing that only one request was 
successful:
+
+```text
+200:    1, 429:    4
 ```
diff --git a/docs/zh/latest/plugins/hmac-auth.md 
b/docs/zh/latest/plugins/hmac-auth.md
index 14264225b..c44604739 100644
--- a/docs/zh/latest/plugins/hmac-auth.md
+++ b/docs/zh/latest/plugins/hmac-auth.md
@@ -6,7 +6,7 @@ keywords:
   - Plugin
   - HMAC Authentication
   - hmac-auth
-description: 本文介绍了关于 Apache APISIX `hmac-auth` 插件的基本信息及使用方法。
+description: hmac-auth 插件支持 HMAC 认证,保证请求的完整性,防止传输过程中的修改,增强 API 的安全性。
 ---
 
 <!--
@@ -30,11 +30,13 @@ description: 本文介绍了关于 Apache APISIX `hmac-auth` 插件的基本信
 
 ## 描述
 
-`hmac-auth` 插件支持 HMAC(基于哈希的消息认证码)身份验证,作为一种确保请求完整性的机制,防止它们在传输过程中被修改。要使用该插件,您需要在 
[Consumers](../terminology/consumer.md) 上配置 HMAC 密钥,并在 Routes 或 Services 上启用该插件。
+`hmac-auth` 插件支持 HMAC(基于哈希的消息认证码)认证,作为一种确保请求完整性的机制,防止它们在传输过程中被修改。要使用该插件,您需要在 
[Consumers](../terminology/consumer.md) 上配置 HMAC 密钥,并在 Routes 或 Services 上启用该插件。
 
-启用后,插件会验证请求的 `Authorization` 标头中的 HMAC 签名,并检查传入请求是否来自可信来源。具体来说,当 APISIX 收到 
HMAC 签名的请求时,会从 `Authorization` 标头中提取密钥 ID。然后,APISIX 会检索相应的消费者配置,包括密钥。如果密钥 ID 
有效且存在,APISIX 会使用请求的 `Date` 标头和密钥生成 HMAC 签名。如果生成的签名与 `Authorization` 
标头中提供的签名匹配,则请求经过身份验证并转发到上游服务。
+当消费者成功通过身份验证后,APISIX 会在将请求代理到上游服务之前向请求添加其他标头,例如 
`X-Consumer-Username`、`X-Credential-Indentifier` 
和其他消费者自定义标头(如果已配置)。上游服务将能够区分消费者并根据需要实现其他逻辑。如果这些值中的任何一个不可用,则不会添加相应的标头。
 
-该插件实现基于 
[draft-cavage-http-signatures](https://www.ietf.org/archive/id/draft-cavage-http-signatures-12.txt)。
+启用后,插件会验证请求的 `Authorization` 标头中的 HMAC 签名,并检查传入的请求是否来自受信任的来源。具体来说,当 APISIX 收到 
HMAC 签名的请求时,会从 `Authorization` 标头中提取密钥 ID。然后,APISIX 会检索相应的消费者配置,包括密钥。如果密钥 ID 
有效且存在,APISIX 将使用请求的 `Date` 标头和密钥生成 HMAC 签名。如果生成的签名与 `Authorization` 
标头中提供的签名匹配,则请求通过身份验证并转发到上游服务。
+
+插件实现基于 
[draft-cavage-http-signatures](https://www.ietf.org/archive/id/draft-cavage-http-signatures-12.txt)。
 
 ## 属性
 
@@ -54,10 +56,13 @@ description: 本文介绍了关于 Apache APISIX `hmac-auth` 插件的基本信
 | signed_headers        | array[string] | 否    |               |               
                              | 客户端请求的 HMAC 签名中应包含的 HMAC 签名头列表。  |
 | validate_request_body | boolean       | 否    | false         |               
               | 如果为 true,则验证请求正文的完整性,以确保在传输过程中没有被篡改。具体来说,插件会创建一个 SHA-256 的 
base64 编码 digest,并将其与 `Digest` 头进行比较。如果 `Digest` 头丢失或 digest 不匹配,验证将失败。         
                 |
 | hide_credentials | boolean       | 否    | false         |                    
          | 如果为 true,则不会将授权请求头传递给上游服务。                        |
+| anonymous_consumer | string    | 否    |          |                           
   | 匿名消费者名称。如果已配置,则允许匿名用户绕过身份验证。                        |
 
 注意:schema 中还定义了 `encrypt_fields = {"secret_key"}`,这意味着该字段将会被加密存储在 etcd 中。具体参考 
[加密存储字段](../plugin-develop.md#加密存储字段)。
 
-## 例子
+## 示例
+
+下面的示例说明了如何在不同场景中使用“hmac-auth”插件。
 
 :::note
 
@@ -69,19 +74,24 @@ admin_key=$(yq '.deployment.admin.admin_key[0].key' 
conf/config.yaml | sed 's/"/
 
 :::
 
-在继续之前,创建一个示例使用者并配置其凭据,该配置将用于下面的所有示例。
+### 在路由上实现 HMAC 身份验证
+
+以下示例演示如何在路由上实现 HMAC 身份验证。您还将在 `Consumer-Custom-Id` 标头中将消费者自定义 ID 
附加到经过身份验证的请求,该 ID 可用于根据需要实现其他逻辑。
 
-创建一个消费者 `john`:
+创建一个带有自定义 ID 标签的消费者 `john`:
 
 ```shell
 curl "http://127.0.0.1:9180/apisix/admin/consumers"; -X PUT \
   -H "X-API-KEY: ${admin_key}" \
   -d '{
-    "username": "john"
+    "username": "john",
+    "labels": {
+      "custom_id": "495aec6a"
+    }
   }'
 ```
 
-创建 `john` 的 `hmac-auth` 凭证:
+为消费者创建 `hmac-auth` 凭证:
 
 ```shell
 curl "http://127.0.0.1:9180/apisix/admin/consumers/john/credentials"; -X PUT \
@@ -97,10 +107,6 @@ curl 
"http://127.0.0.1:9180/apisix/admin/consumers/john/credentials"; -X PUT \
   }'
 ```
 
-### 在路由上实现 HMAC 身份验证
-
-以下示例展示了如何在路由上实现 HMAC 身份验证。
-
 使用 `hmac-auth` 插件的默认配置创建路由:
 
 ```shell
@@ -122,7 +128,7 @@ curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
   }'
 ```
 
-生成签名。您可以使用以下 Python 代码片段或您选择的其他技术栈:
+生成签名。您可以使用以下 Python 代码片段或其他技术栈:
 
 ```python title="hmac-sig-header-gen.py"
 import hmac
@@ -130,21 +136,21 @@ import hashlib
 import base64
 from datetime import datetime, timezone
 
-key_id = "john-key"                # 密钥 ID
-Secret_key = b"john-secret-key"    # 秘密密钥
-request_method = "GET"             # HTTP 方法
-request_path = "/get"              # 路由 URI
-algorithm= "hmac-sha256"           # 可以在 allowed_algorithms 中使用其他算法
+key_id = "john-key"                # key id
+secret_key = b"john-secret-key"    # secret key
+request_method = "GET"             # HTTP method
+request_path = "/get"              # Route URI
+algorithm= "hmac-sha256"           # can use other algorithms in 
allowed_algorithms
 
-# 获取当前的 GMT 日期时间
-# 注意:时钟偏差后签名将失效(默认 300s)
-# 签名失效后可以重新生成,或者增加时钟
-# 倾斜以延长建议的安全边界内的有效性
+# get current datetime in GMT
+# note: the signature will become invalid after the clock skew (default 300s)
+# you can regenerate the signature after it becomes invalid, or increase the 
clock
+# skew to prolong the validity within the advised security boundary
 gmt_time = datetime.now(timezone.utc).strftime('%a, %d %b %Y %H:%M:%S GMT')
 
-# 构造签名字符串(有序)
-# 日期和任何后续的自定义标头应小写并用
-# 单空格字符,即 `<key>:<space><value>`
+# construct the signing string (ordered)
+# the date and any subsequent custom headers should be lowercased and 
separated by a
+# single space character, i.e. `<key>:<space><value>`
 # 
https://datatracker.ietf.org/doc/html/draft-cavage-http-signatures-12#section-2.1.6
 signing_string = (
   f"{key_id}\n"
@@ -152,11 +158,11 @@ signing_string = (
   f"date: {gmt_time}\n"
 )
 
-# 创建签名
+# create signature
 signature = hmac.new(secret_key, signing_string.encode('utf-8'), 
hashlib.sha256).digest()
 signature_base64 = base64.b64encode(signature).decode('utf-8')
 
-# 构造请求头
+# construct the request headers
 headers = {
   "Date": gmt_time,
   "Authorization": (
@@ -166,7 +172,7 @@ headers = {
   )
 }
 
-# 打印请求头
+# print headers
 print(headers)
 ```
 
@@ -204,6 +210,7 @@ curl -X GET "http://127.0.0.1:9080/get"; \
     "X-Amzn-Trace-Id": "Root=1-66d96513-2e52d4f35c9b6a2772d667ea",
     "X-Consumer-Username": "john",
     "X-Credential-Identifier": "cred-john-hmac-auth",
+    "X-Consumer-Custom-Id": "495aec6a",
     "X-Forwarded-Host": "127.0.0.1"
   },
   "origin": "192.168.65.1, 34.0.34.160",
@@ -211,13 +218,13 @@ curl -X GET "http://127.0.0.1:9080/get"; \
 }
 ```
 
-### 向上游隐藏授权信息
+### Hide Authorization Information From Upstream
 
-如 [上一个示例](#implement-hmac-authentication-on-a-route) 所示,传递给上游的 `Authorization` 
标头包含签名和所有其他详细信息。这可能会带来安全风险。
+As seen the in the [last example](#implement-hmac-authentication-on-a-route), 
the `Authorization` header passed to the Upstream includes the signature and 
all other details. This could potentially introduce security risks.
 
-以下示例展示了如何防止这些信息被发送到上游服务。
+The following example demonstrates how to prevent these information from being 
sent to the Upstream service.
 
-更新插件配置以将 `hide_credentials` 设置为 `true`:
+Update the plugin configuration to set `hide_credentials` to `true`:
 
 ```shell
 curl "http://127.0.0.1:9180/apisix/admin/routes/hmac-auth-route"; -X PATCH \
@@ -231,7 +238,7 @@ curl 
"http://127.0.0.1:9180/apisix/admin/routes/hmac-auth-route"; -X PATCH \
 }'
 ```
 
-发送以下请求:
+Send a request to the route:
 
 ```shell
 curl -X GET "http://127.0.0.1:9080/get"; \
@@ -239,7 +246,7 @@ curl -X GET "http://127.0.0.1:9080/get"; \
   -H 'Authorization: Signature 
keyId="john-key",algorithm="hmac-sha256",headers="@request-target 
date",signature="wWfKQvPDr0wHQ4IHdluB4IzeNZcj0bGJs2wvoCOT5rM="'
 ```
 
-您应该看到 `HTTP/1.1 200 OK` 响应,并注意到 `Authorization` 标头已被完全删除:
+You should see an `HTTP/1.1 200 OK` response and notice the `Authorization` 
header is entirely removed:
 
 ```json
 {
@@ -258,11 +265,37 @@ curl -X GET "http://127.0.0.1:9080/get"; \
 }
 ```
 
-### 启用主体验证
+### Enable Body Validation
+
+The following example demonstrates how to enable body validation to ensure the 
integrity of the request body.
+
+Create a consumer `john`:
 
-以下示例显示如何启用主体验证以确保请求主体的完整性。
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/consumers"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "username": "john"
+  }'
+```
 
-使用 `hmac-auth` 插件创建路由,如下所示:
+为消费者创建 `hmac-auth` 凭证:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/consumers/john/credentials"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "cred-john-hmac-auth",
+    "plugins": {
+      "hmac-auth": {
+        "key_id": "john-key",
+        "secret_key": "john-secret-key"
+      }
+    }
+  }'
+```
+
+Create a Route with the `hmac-auth` plugin as such:
 
 ```shell
 curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
@@ -285,7 +318,7 @@ curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
   }'
 ```
 
-生成签名。您可以使用以下 Python 代码片段或您选择的其他技术栈:
+生成签名。您可以使用以下 Python 代码片段或其他技术栈:
 
 ```python title="hmac-sig-digest-header-gen.py"
 import hmac
@@ -293,22 +326,22 @@ import hashlib
 import base64
 from datetime import datetime, timezone
 
-key_id = "john-key"             # 密钥 ID
-Secret_key = b"john-secret-key" # 秘密密钥
-request_method = "POST"         # HTTP 方法
-request_path = "/post"          # 路由 URI
-algorithms= "hmac-sha256"       # 可以在 allowed_algorithms 中使用其他算法
-body = '{"name": "world"}'      # 请求正文示例
-
-# 获取当前的 GMT 日期时间
-# 注意:时钟偏差(默认 300s)后签名将失效。
-# 签名失效后可以重新生成,或者增加时钟
-# 倾斜以延长建议的安全边界内的有效性
+key_id = "john-key"                 # key id
+secret_key = b"john-secret-key"     # secret key
+request_method = "POST"             # HTTP method
+request_path = "/post"              # Route URI
+algorithm= "hmac-sha256"            # can use other algorithms in 
allowed_algorithms
+body = '{"name": "world"}'          # example request body
+
+# get current datetime in GMT
+# note: the signature will become invalid after the clock skew (default 300s).
+# you can regenerate the signature after it becomes invalid, or increase the 
clock
+# skew to prolong the validity within the advised security boundary
 gmt_time = datetime.now(timezone.utc).strftime('%a, %d %b %Y %H:%M:%S GMT')
 
-# 构造签名字符串(有序)
-# 日期和任何后续的自定义标头应小写并用
-# 单空格字符,即 `<key>:<space><value>`
+# construct the signing string (ordered)
+# the date and any subsequent custom headers should be lowercased and 
separated by a
+# single space character, i.e. `<key>:<space><value>`
 # 
https://datatracker.ietf.org/doc/html/draft-cavage-http-signatures-12#section-2.1.6
 signing_string = (
     f"{key_id}\n"
@@ -316,15 +349,15 @@ signing_string = (
     f"date: {gmt_time}\n"
 )
 
-# 创建签名
+# create signature
 signature = hmac.new(secret_key, signing_string.encode('utf-8'), 
hashlib.sha256).digest()
 signature_base64 = base64.b64encode(signature).decode('utf-8')
 
-# 创建请求正文的 SHA-256 digest 并对其进行 Base64 编码
+# create the SHA-256 digest of the request body and base64 encode it
 body_digest = hashlib.sha256(body.encode('utf-8')).digest()
 body_digest_base64 = base64.b64encode(body_digest).decode('utf-8')
 
-# 构造请求头
+# construct the request headers
 headers = {
     "Date": gmt_time,
     "Digest": f"SHA-256={body_digest_base64}",
@@ -335,7 +368,7 @@ headers = {
     )
 }
 
-# 打印请求头
+# print headers
 print(headers)
 ```
 
@@ -391,7 +424,7 @@ curl "http://127.0.0.1:9080/post"; -X POST \
 }
 ```
 
-如果您发送的请求没有 digest 或 digest 无效:
+如果您发送的请求没有摘要或摘要无效:
 
 ```shell
 curl "http://127.0.0.1:9080/post"; -X POST \
@@ -409,9 +442,35 @@ curl "http://127.0.0.1:9080/post"; -X POST \
 
 ### 强制签名标头
 
-以下示例展示了如何强制在请求的 HMAC 签名中对某些标头进行签名。
+以下示例演示了如何强制在请求的 HMAC 签名中对某些标头进行签名。
+
+创建消费者 `john`:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/consumers"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "username": "john"
+  }'
+```
+
+为消费者创建 `hmac-auth` 凭证:
 
-使用 `hmac-auth` 插件创建路由,该路由要求 HMAC 签名中存在三个标头:
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/consumers/john/credentials"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "cred-john-hmac-auth",
+    "plugins": {
+      "hmac-auth": {
+        "key_id": "john-key",
+        "secret_key": "john-secret-key"
+      }
+    }
+  }'
+```
+
+使用 `hmac-auth` 插件创建路由,该插件要求 HMAC 签名中存在三个标头:
 
 ```shell
 curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
@@ -422,7 +481,7 @@ curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
     "methods": ["GET"],
     "plugins": {
       "hmac-auth": {
-        "signed_headers": ["date","x-custom-header-a", "x-custom-header-b"]
+        "signed_headers": ["date","x-custom-header-a","x-custom-header-b"]
       }
     },
     "upstream": {
@@ -434,7 +493,7 @@ curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
   }'
 ```
 
-生成签名。您可以使用以下 Python 代码片段或您选择的其他技术栈:
+生成签名。您可以使用以下 Python 代码片段或其他技术栈:
 
 ```python title="hmac-sig-req-header-gen.py"
 import hmac
@@ -442,23 +501,23 @@ import hashlib
 import base64
 from datetime import datetime, timezone
 
-key_id = "john-key"             # 密钥 ID
-Secret_key = b"john-secret-key" # 秘密密钥
-request_method = "GET"          # HTTP 方法
-request_path = "/get"           # 路由 URI
-algorithms= "hmac-sha256"       # 可以在 allowed_algorithms 中使用其他算法
-custom_header_a = "hello123"    # 必需的自定义标头
-custom_header_b = "world456"    # 必需的自定义标头
-
-# 获取当前的 GMT 日期时间
-# 注意:时钟偏差后签名将失效(默认 300s)
-# 签名失效后可以重新生成,或者增加时钟
-# 倾斜以延长建议的安全边界内的有效性
+key_id = "john-key"                # key id
+secret_key = b"john-secret-key"    # secret key
+request_method = "GET"             # HTTP method
+request_path = "/get"              # Route URI
+algorithm= "hmac-sha256"           # can use other algorithms in 
allowed_algorithms
+custom_header_a = "hello123"       # required custom header
+custom_header_b = "world456"       # required custom header
+
+# get current datetime in GMT
+# note: the signature will become invalid after the clock skew (default 300s)
+# you can regenerate the signature after it becomes invalid, or increase the 
clock
+# skew to prolong the validity within the advised security boundary
 gmt_time = datetime.now(timezone.utc).strftime('%a, %d %b %Y %H:%M:%S GMT')
 
-# 构造签名字符串(有序)
-# 日期和任何后续的自定义标头应小写并用
-# 单空格字符,即 `<key>:<space><value>`
+# construct the signing string (ordered)
+# the date and any subsequent custom headers should be lowercased and 
separated by a
+# single space character, i.e. `<key>:<space><value>`
 # 
https://datatracker.ietf.org/doc/html/draft-cavage-http-signatures-12#section-2.1.6
 signing_string = (
     f"{key_id}\n"
@@ -468,11 +527,11 @@ signing_string = (
     f"x-custom-header-b: {custom_header_b}\n"
 )
 
-# 创建签名
+# create signature
 signature = hmac.new(secret_key, signing_string.encode('utf-8'), 
hashlib.sha256).digest()
 signature_base64 = base64.b64encode(signature).decode('utf-8')
 
-# 构造请求头
+# construct the request headers
 headers = {
     "Date": gmt_time,
     "Authorization": (
@@ -484,7 +543,7 @@ headers = {
     "x-custom-header-b": custom_header_b
 }
 
-# 打印请求头
+# print headers
 print(headers)
 ```
 
@@ -533,21 +592,169 @@ curl -X GET "http://127.0.0.1:9080/get"; \
 }
 ```
 
-## 删除插件
+### 匿名消费者的速率限制
 
-当你需要在路由上删除该插件时,可以通过以下命令删除相应的 JSON 配置,APISIX 将会自动重新加载相关配置,无需重启服务:
+以下示例演示了如何为常规消费者和匿名消费者配置不同的速率限制策略,其中匿名消费者不需要进行身份验证,配额较少。
+
+创建常规消费者 `john`,并配置 `limit-count` 插件,以允许 30 秒内的配额为 3:
 
 ```shell
-curl http://127.0.0.1:9180/apisix/admin/routes/1 \
--H "X-API-KEY: $admin_key" -X PUT -d '
-{
-    "uri": "/index.html",
-    "plugins": {},
+curl "http://127.0.0.1:9180/apisix/admin/consumers"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "username": "john",
+    "plugins": {
+      "limit-count": {
+        "count": 3,
+        "time_window": 30,
+        "rejected_code": 429
+      }
+    }
+  }'
+```
+
+为消费者 `john` 创建 `hmac-auth` 凭证:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/consumers/john/credentials"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "cred-john-hmac-auth",
+    "plugins": {
+      "hmac-auth": {
+        "key_id": "john-key",
+        "secret_key": "john-secret-key"
+      }
+    }
+  }'
+```
+
+创建匿名用户 `anonymous`,并配置 `limit-count` 插件,以允许 30 秒内配额为 1:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/consumers"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "username": "anonymous",
+    "plugins": {
+      "limit-count": {
+        "count": 1,
+        "time_window": 30,
+        "rejected_code": 429
+      }
+    }
+  }'
+```
+
+创建路由并配置 `hmac-auth` 插件以接受匿名消费者 `anonymous` 绕过身份验证:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "hmac-auth-route",
+    "uri": "/get",
+    "methods": ["GET"],
+    "plugins": {
+      "hmac-auth": {
+        "anonymous_consumer": "anonymous"
+      }
+    },
     "upstream": {
-        "type": "roundrobin",
-        "nodes": {
-            "127.0.0.1:1980": 1
-        }
+      "type": "roundrobin",
+      "nodes": {
+        "httpbin.org:80": 1
+      }
     }
-}'
+  }'
+```
+
+生成签名。您可以使用以下 Python 代码片段或其他技术栈:
+
+```python title="hmac-sig-header-gen.py"
+import hmac
+import hashlib
+import base64
+from datetime import datetime, timezone
+
+key_id = "john-key"                # key id
+secret_key = b"john-secret-key"    # secret key
+request_method = "GET"             # HTTP method
+request_path = "/get"              # Route URI
+algorithm= "hmac-sha256"           # can use other algorithms in 
allowed_algorithms
+
+# get current datetime in GMT
+# note: the signature will become invalid after the clock skew (default 300s)
+# you can regenerate the signature after it becomes invalid, or increase the 
clock
+# skew to prolong the validity within the advised security boundary
+gmt_time = datetime.now(timezone.utc).strftime('%a, %d %b %Y %H:%M:%S GMT')
+
+# construct the signing string (ordered)
+# the date and any subsequent custom headers should be lowercased and 
separated by a
+# single space character, i.e. `<key>:<space><value>`
+# 
https://datatracker.ietf.org/doc/html/draft-cavage-http-signatures-12#section-2.1.6
+signing_string = (
+  f"{key_id}\n"
+  f"{request_method} {request_path}\n"
+  f"date: {gmt_time}\n"
+)
+
+# create signature
+signature = hmac.new(secret_key, signing_string.encode('utf-8'), 
hashlib.sha256).digest()
+signature_base64 = base64.b64encode(signature).decode('utf-8')
+
+# construct the request headers
+headers = {
+  "Date": gmt_time,
+  "Authorization": (
+    f'Signature keyId="{key_id}",algorithm="{algorithm}",'
+    f'headers="@request-target date",'
+    f'signature="{signature_base64}"'
+  )
+}
+
+# print headers
+print(headers)
+```
+
+运行脚本:
+
+```shell
+python3 hmac-sig-header-gen.py
+```
+
+您应该看到打印的请求标头:
+
+```text
+{'Date': 'Mon, 21 Oct 2024 17:31:18 GMT', 'Authorization': 'Signature 
keyId="john-key",algorithm="hmac-sha256",headers="@request-target 
date",signature="ztFfl9w7LmCrIuPjRC/DWSF4gN6Bt8dBBz4y+u1pzt8="'}
+```
+
+使用生成的标头发送五个连续的请求:
+
+```shell
+resp=$(seq 5 | xargs -I{} curl "http://127.0.0.1:9080/anything"; -H "Date: Mon, 
21 Oct 2024 17:31:18 GMT" -H 'Authorization: Signature 
keyId="john-key",algorithm="hmac-sha256",headers="@request-target 
date",signature="ztFfl9w7LmCrIuPjRC/DWSF4gN6Bt8dBBz4y+u1pzt8="' -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)。
+
+```text
+200:    3, 429:    2
+```
+
+发送五个匿名请求:
+
+```shell
+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
+```
+
+您应该看到以下响应,表明只有一个请求成功:
+
+```text
+200:    1, 429:    4
 ```


Reply via email to