a6-plugin-key-auth
概览
key-auth 插件使用 API Key 对请求进 行认证。客户端会在
请求头、查询参数或 Cookie 中携带 key。Apache APISIX会根据该 key 查找
消费者凭证;匹配成功后,会携带消费者身份
相关消费者身份请求头。认证失败时会返回 401 Unauthorized。
适用场景
- 使用简单的 API Key 认证保护路由
- 识别调用 API 的消费者
- 与限流结合,实现分层访问(已认证与匿名)
- 对上游隐藏凭证。
插件配置参考(路由/服务)
| 字段 | 类型 | 是否必填 | 默认值 | 说明 |
|---|---|---|---|---|
header | string | 否 | "apikey" | 提取 API Key 的请求头名称 |
query | string | 否 | "apikey" | 查询参数名称(优先级低于请求头) |
hide_credentials | boolean | 否 | false | 转发到上游前从请求中移除 Key |
anonymous_consumer | string | 否 | — | 未认证请求使用的消费者用户名 |
realm | string | 否 | "key" | 401 响应中 WWW-Authenticate 响应头的 realm |
消费者凭证参考
| 字段 | 类型 | 是否必填 | 说明 |
|---|---|---|---|
key | string | 是 | 消费者的唯一 API Key,存储到 etcd 时自动加密。 |
Key 查找优先级
- 请求头(默认:
apikey):优先检查 - 查询参数(默认:
apikey):请求头不存在时检查 - 如果两者都不存在,则返回
401 Unauthorized和"Missing API key in request"
分步操作:在路由上启用 key-auth
1. 创建消费者
a6 consumer create -f - <<'EOF'
{
"username": "alice"
}
EOF
2. 为消费者添加 key-auth 凭证
使用 Admin API(凭证是消费者的子资源):
curl "$(a6 context current -o json | jq -r .server)/apisix/admin/consumers/alice/credentials" \
-X PUT \
-H "X-API-KEY: $(a6 context current -o json | jq -r .api_key)" \
-d '{
"id": "cred-alice-key-auth",
"plugins": {
"key-auth": {
"key": "alice-secret-key-001"
}
}
}'
3. 创建启用 key-auth 的路由
a6 route create -f - <<'EOF'
{
"id": "protected-api",
"uri": "/api/*",
"plugins": {
"key-auth": {}
},
"upstream": {
"type": "roundrobin",
"nodes": {
"backend:8080": 1
}
}
}
EOF
4. 验证认证
# Should succeed (200)
curl -i http://127.0.0.1:9080/api/users -H "apikey: alice-secret-key-001"
# Should fail (401)
curl -i http://127.0.0.1:9080/api/users