forward-auth
forward-auth
插件巧妙地将身份认证和授权逻辑移到了一个专门的外部服务中,APISIX 将用户的请求转发给认证服务并阻塞原始请求,然后在认证服务下以非 2xx 状态响应时进行结果替换。
Scheme | HTTP Method | Host | URI | Source IP |
---|---|---|---|---|
X-Forwarded-Proto | X-Forwarded-Method | X-Forwarded-Host | X-Forwarded-Uri | X-Forwarded-For |
首先,你需要设置一个外部认证服务。以下示例使用的是 Apache APISIX 无服务器插件模拟服务:
curl -X PUT 'http://127.0.0.1:9080/apisix/admin/routes/1' \
-H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' \
-d '{
"uri": "/headers",
"plugins": {
"uri": "http://127.0.0.1:9080/auth",
"request_headers": ["Authorization"],
"upstream_headers": ["X-User-ID"],
"client_headers": ["Location"]
}
"upstream": {
"nodes": {
"httpbin.org:80": 1
},
"type": "roundrobin"
}
}'
完成上述配置后,可通过以下三种方式进行测试:
- 在请求头中发送认证的详细信息:
curl http://127.0.0.1:9080/headers -H 'Authorization: 123'
- 转发认证服务响应头到 Upstream。
curl http://127.0.0.1:9080/headers -H 'Authorization: 321'
{
"headers": {
"Authorization": "321",
"Next": "More-headers"
}
- 当授权失败时,认证服务可以向用户发送自定义响应:
HTTP/1.1 403 Forbidden
Location: http://example.com/auth
curl http://127.0.0.1:9080/apisix/admin/routes/1 \
-H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
{
"methods": ["GET"],
"uri": "/hello",
"plugins": {},
"upstream": {
"type": "roundrobin",
"nodes": {
"httpbin.org:80": 1
}
}