nginx_auth_request - meetbill/butterfly-nginx GitHub Wiki

认证及鉴权

验证流程

NGINX ---- auth request ----> /auth/verification
                                  |         |
  |     <---      200  <------  SUCCESS    FAILED -----> 401  -----> /butterfly_401
  |
  ----> underlying request ----> BACKEND SERVER

传送门

FAQ

auth_request 是否可以直接将响应直接返回给客户端

答案是不行的,auth_request 返回状态码为 401 时,会默认输出 nginx 的 401 页面

可以通过如下方式进行处理,添加 401 默认处理页面

nginx 配置,认证失败后,会自动内部转到 /butterfly_401

location = /auth/verification {
    internal;
    proxy_pass http://127.0.0.1:8001;
    proxy_pass_request_body off;
    proxy_set_header Content-Length "";
    proxy_set_header X-Original-URI $request_uri;
    proxy_set_header Host  $host:$server_port;
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header X-Real-PORT $remote_port;
    proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
}

#对 / 所有做负载均衡 + 反向代理
location / {
    auth_request        /auth/verification;
    auth_request_set    $butterfly_location $upstream_http_location;
    error_page 401    = /butterfly_401;
    proxy_redirect off;
    # 后端的 Web 服务器可以通过 X-Forwarded-For 获取用户真实 IP
    proxy_set_header Host  $host:$server_port;
    proxy_set_header  X-Real-IP  $remote_addr;
    proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
    proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
    proxy_pass        http://backend;
}

location  = /butterfly_401 {
    internal;
    default_type application/json;
    if ($butterfly_location) {
        return 401 '{"success":false,"message":"You are not authorized","data":{"Target_url":"$butterfly_location"}}';
    }
}

butterfly 认证失败时,Response 的 header 中添加 Location,值为要登录的地址

protocol = "http://"
host = req.wsgienv.get("HTTP_HOST")
login_url = protocol + host + "/auth/ssologin"
return http_code ,context ,[("Location",login_url)]

nginx http auth 请求模块仅返回默认错误页面

Nginx auth_request 如何处理程序访问 POST 请求体?

auth_request 模块总是用空缓冲区替换 POST 主体。

auth 子请求是通过 HTTP GET 方法发送的,而不是 POST. 由于 GET 没有 body, body 被丢弃

Nginx auth_request handler accessing POST request body?

传送门

官方文档