15.基于子请求验证服务
NGINX可以使用外部服务器或服务验证对您网站的每个请求。为了执行身份验证,NGINX向验证子请求的外部服务器发出HTTP子请求。如果子请求返回响应代码 2xx,则允许访问,如果返回 401或 403,则拒绝访问。这种类型的身份验证允许实现各种身份验证方案,例如多因素身份验证,或允许实现 LDAP 或 OAuth 身份验证。
配置 NGINX
-
确保您的NGINX是使用
with-http_auth_request_module配置选项编译的。运行以下命令并验证输出是否包含 --with-http_auth_request_module:$ nginx -V 2>&1 | grep -- 'http_auth_request_module' -
在需要请求身份验证的location中,指定 auth_request 指令,在该指令中指定授权子请求将转发到的内部位置:
location /private/ {
auth_request /auth;
#...
}在这里,对于对 /private 的每个请求,将向内部 /auth 位置发出一个子请求。
-
指定内部位置(internal location)和此location内的 proxy_pass 指令,该指令将身份验证子请求代理到身份验证服务器或服务:
location = /auth {
internal;
proxy_pass http://auth-server;
#...
} -
由于身份验证子请求会丢弃请求正文,因此您需要将 proxy_pass_request_body 指令设置为
off字符串,并将Content-Length标头设置为 null 字符串:location = /auth {
internal;
proxy_pass http://auth-server;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
#...
} -
使用 proxy_set_header 指令传递带有参数的完整原始请求 URI:
location = /auth {
internal;
proxy_pass http://auth-server;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header X-Original-URI $request_uri;
} -
作为一个选项,您可以使用 auth_request_set 指令根据子请求的结果设置变量值:
location /private/ {
auth_request /auth;
auth_request_set $auth_status $upstream_status;
}
完整示例
此示例将前面的步骤汇总为一个配置:
http {
#...
server {
#...
location /private/ {
auth_request /auth;
auth_request_set $auth_status $upstream_status;
}
location = /auth {
internal;
proxy_pass http://auth-server;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header X-Original-URI $request_uri;
}
}
}