forward-auth

    forward-auth 插件巧妙地将身份认证和授权逻辑移到了一个专门的外部服务中,APISIX 将用户的请求转发给认证服务并阻塞原始请求,然后在认证服务下以非 2xx 状态响应时进行结果替换。

    SchemeHTTP MethodHostURISource IP
    X-Forwarded-ProtoX-Forwarded-MethodX-Forwarded-HostX-Forwarded-UriX-Forwarded-For

    首先,你需要设置一个外部认证服务。以下示例使用的是 Apache APISIX 无服务器插件模拟服务:

    1. curl -X PUT 'http://127.0.0.1:9080/apisix/admin/routes/1' \
    2. -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' \
    3. -d '{
    4. "uri": "/headers",
    5. "plugins": {
    6. "uri": "http://127.0.0.1:9080/auth",
    7. "request_headers": ["Authorization"],
    8. "upstream_headers": ["X-User-ID"],
    9. "client_headers": ["Location"]
    10. }
    11. "upstream": {
    12. "nodes": {
    13. "httpbin.org:80": 1
    14. },
    15. "type": "roundrobin"
    16. }
    17. }'

    完成上述配置后,可通过以下三种方式进行测试:

    • 在请求头中发送认证的详细信息:
    1. curl http://127.0.0.1:9080/headers -H 'Authorization: 123'
    • 转发认证服务响应头到 Upstream。
    1. curl http://127.0.0.1:9080/headers -H 'Authorization: 321'
    1. {
    2. "headers": {
    3. "Authorization": "321",
    4. "Next": "More-headers"
    5. }
    • 当授权失败时,认证服务可以向用户发送自定义响应:
    1. HTTP/1.1 403 Forbidden
    2. Location: http://example.com/auth
    1. curl http://127.0.0.1:9080/apisix/admin/routes/1 \
    2. -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
    3. {
    4. "methods": ["GET"],
    5. "uri": "/hello",
    6. "plugins": {},
    7. "upstream": {
    8. "type": "roundrobin",
    9. "nodes": {
    10. "httpbin.org:80": 1
    11. }
    12. }