在访问日志中记录消费者标签
在 APISIX 的访问日志中记录消费者标签可以提高 API 流量的可见性和控制力。通过捕获消费者标签,组织可以轻松识别哪些客户端正在访问特定路由,跟踪使用模式 ,并根据这些标签实施安全策略。
本指南将向你展示如何在网关的访问日志中记录消费者标签。
备注
Ingress Controller 目前不支持配置消费者标签。
前置条件
创建并在访问日志中使用新变量
在 配置文件 中,为消费者标签初始化一个自定义变量,并为其分配默认值 -。在此示例中,你将初始化一个名为 $consumer_company 的变量,但你始终可以根据需要初始化更多变量:
conf/config.yaml
nginx_config:
http_server_location_configuration_snippet: |
set $consumer_company "-";
在同一文件中,更新访问日志格式以包含新初始化的变量:
conf/config.yaml
nginx_config:
http:
access_log_format: >-
$remote_addr - $remote_user [$time_local] $http_host \"$request\" $status $body_bytes_sent $request_time \"$http_referer\" \"$http_user_agent\" $upstream_addr $upstream_status $upstream_response_time \"$upstream_scheme://$upstream_host$upstream_uri\" "$consumer_company"
重新加载 APISIX 以使更改生效。
为新变量赋值
使用 无服务器函数 为新变量分配消费者标签值。
例如,将 serverless 插件配置为全局插件,如下所示:
curl "http://127.0.0.1:9180/apisix/admin/global_rules" -X PUT -d '
{
"id": "serverless-consumer-label",
"plugins": {
"serverless-pre-function": {
"phase": "log",
"functions": [
"return function (conf, ctx) ngx.var.consumer_company = ctx.consumer and ctx.consumer.labels and ctx.consumer.labels[\"company\"] or \"unknown\" end"
]
}
}
}'
该函数获取消费者标签 company 值并将其分配给 consumer_company 变量。如果消费者没有 company 标签,consumer_company 变量值将被分配为 unknown。
配置消费者和身份验证
创建一个带有自定义标签 company 的消费者 john:
curl "http://127.0.0.1:9180/apisix/admin/consumers" -X PUT -d '
{
"username": "john",
"labels": {
"company": "smart-technology"
}
}'
为消费者创建 key-auth 凭证:
curl "http://127.0.0.1:9180/apisix/admin/consumers/john/credentials" -X PUT -d '
{
"id": "cred-john-key-auth",
"plugins": {
"key-auth": {
"key": "john-key"
}
}
}'
创建一个路由并在该路由上启用 key-auth:
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT -d '
{
"id": "key-auth-route",
"uri": "/anything",
"plugins": {
"key-auth": {}
},
"upstream": {
"type": "roundrobin",
"nodes": {
"httpbin.org:80": 1
}
}
}'
验证
使用有效密钥向路由发送请求:
curl -i "http://127.0.0.1:9080/anything" -H 'apikey: john-key'
你应该收到 HTTP/1.1 200 OK 响应,并在访问日志中看到以下内容,其中公司名称记录为 smart-technology:
192.168.107.1 - - [18/Mar/2025:09:17:28 +0000] 127.0.0.1:9080 "GET /anything HTTP/1.1" 200 508 1.260 "-" "curl/8.6.0" 13.210.43.76:80 200 1.153 "http://127.0.0.1:9080" "smart-technology"
向路由发送不带密钥的请求:
curl -i "http://127.0.0.1:9080/anything"
你应该看到 HTTP/1.1 401 Unauthorized 响应,并在访问日志中看到以下内容,其中公司名称记录为 unknown:
192.168.107.1 - - [18/Mar/2025:09:18:27 +0000] 127.0.0.1:9080 "GET /anything HTTP/1.1" 401 52 0.000 "-" "curl/8.6.0" - - - "http://127.0.0.1:9080" "unknown"