在访问日志中记录消费者标签
在 API 网关的访问日志中记录消费者标签,可以提高 API 流量的可见性和可控性。通过捕获消费者标签,组织可以轻松识别访问特定路由的客户端、追踪使用模式,并根据这些标签执行安全策略。
本指南介绍如何在网关访问日志中记录消费者标签。
前置要求
在访问日志中创建并使用新变量
在网关配置文件中,为消费者标签初始化一个自定义变量,并将默认值设为 -。本例初始化名为 $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"
重新加载网关,使更改生效。
为新变量赋值
使用无服务器函数将消费者标签的值赋给新变量。
例如,将 serverless-pre-function 插件配置为全局插件,并使用以下配置:
{
"phase": "rewrite",
"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。
配置消费者和身份验证
创建一个名为 john 的消费者,为其设置 company: smart-technology 标签,并将该消费者的 Key Authentication 凭据配置为 john-key。
接下来,创建路由并启用 Key Authentication。
验证
使用有效 Key 向路由发送请求:
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"
不带 Key 向路由发送请求:
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"