跳到主要内容
版本:3.10.x

API7 网关 AI Agent Skill:basic-auth 插件

概览

basic-auth 插件使用 HTTP Basic Authentication(RFC 7617)对请求进行认证。消费者注册用户名和密码;客户端在 Authorization: Basic <base64> 请求头中发送凭证。API7 企业版会解码并根据消费者凭证进行校验;校验通过后,请求会携带消费者身份请求头转发。

适用场景

  • 为 API 提供简单的用户名/密码认证
  • 快速保护内部或开发环境 API
  • 与原生支持 HTTP Basic Auth 的工具集成,例如浏览器、curl、Postman

插件配置参考(路由/服务)

字段类型是否必填默认值说明
hide_credentialsbooleanfalse转发到上游前移除 Authorization 请求头
anonymous_consumerstring未认证请求使用的消费者用户名
realmstring"basic"401 响应中 WWW-Authenticate 响应头的 realm

消费者凭证参考

字段类型是否必填说明
usernamestring消费者的唯一用户名
passwordstring消费者密码,会在数据库中自动加密

分步操作:在路由上启用 basic-auth

1. 创建消费者

a7 consumer create -g default -f - <<'EOF'
{
"username": "alice"
}
EOF

2. 添加 basic-auth 凭证

curl -k "https://$(a7 context current -o json | jq -r .server):7443/apisix/admin/consumers/alice/credentials" \
-X PUT \
-H "X-API-KEY: $(a7 context current -o json | jq -r .token)" \
-d '{
"id": "cred-alice-basic-auth",
"plugins": {
"basic-auth": {
"username": "alice",
"password": "alice-password-123"
}
}
}'

3. 创建启用 basic-auth 的路由

a7 route create -g default -f - <<'EOF'
{
"id": "basic-protected",
"uri": "/api/*",
"plugins": {
"basic-auth": {}
},
"upstream": {
"type": "roundrobin",
"nodes": [{"host": "backend", "port": 8080, "weight": 1}]
}
}
EOF

4. 验证认证

# 使用 curl 的 -u 标志(发送 Authorization: Basic 请求头)
curl -i http://127.0.0.1:9080/api/users -u alice:alice-password-123

# 使用显式请求头("alice:alice-password-123" 的 Base64 编码)
curl -i http://127.0.0.1:9080/api/users \
-H "Authorization: Basic YWxpY2U6YWxpY2UtcGFzc3dvcmQtMTIz"

# 应该失败(401)
curl -i http://127.0.0.1:9080/api/users

常见模式

对上游隐藏凭证

{
"plugins": {
"basic-auth": {
"hide_credentials": true
}
}
}

Authorization 请求头会在到达后端前被移除。生产环境中请始终 启用该配置,以防凭证泄露。

匿名消费者与限流

a7 consumer create -g default -f - <<'EOF'
{
"username": "anonymous",
"plugins": {
"limit-count": {
"count": 10,
"time_window": 60,
"rejected_code": 429
}
}
}
EOF
{
"plugins": {
"basic-auth": {
"anonymous_consumer": "anonymous"
}
}
}

携带有效凭证的请求会关联到已认证消费者;无凭证请求则关联到配置了限流的匿名消费者。

添加到上游的请求头

请求头
X-Consumer-Username消费者用户名
X-Credential-Identifier凭证 ID
X-Consumer-Custom-Id消费者的 labels.custom_id(如已设置)
Authorization原始请求头(除非设置了 hide_credentials: true

故障排查

现象原因修复方式
401 Unauthorized缺少凭证或凭证错误检查用户名和密码,并确认 Base64 编码正确
上游日志中可见凭证hide_credentials 为 false设置 hide_credentials: true
浏览器未弹出登录对话框缺少 WWW-Authenticate 请求头确认插件已启用,并检查 realm 设置
匿名用户未生效未设置 anonymous_consumer创建消费者,并在路由插件上设置该字段

配置同步示例

version: "1"
gateway_groups:
- name: default
consumers:
- username: alice
routes:
- id: basic-protected
uri: /api/*
plugins:
basic-auth: {}
upstream:
type: roundrobin
nodes:
- host: backend
port: 8080
weight: 1

注意:消费者凭证(username/password)必须单独创建,并通过 Admin API 管理;a7 config sync 会管理消费者资源,但凭证属于子资源。


本页面由 api7/a7 仓库中的 a7-plugin-basic-auth/SKILL.md 生成。你可以在 AI Agent Skills 页面查看所有技能。