介绍
NGINX和NGINX Plus可以通过外部服务器或服务验证每个对您网站的请求。为了执行身份验证,NGINX向验证子请求的外部服务器发出HTTP子请求。如果子请求返回2xx响应代码,则允许访问;如果子请求返回401或403,则拒绝访问。此类身份验证允许实现各种身份验证方案,例如多因素身份验证,或者允许实现LDAP或OAuth身份验证。
先决条件
- NGINX Plus或NGINX开源版
- 外部认证服务器或服务
配置NGINX和NGINX Plus
- 确保使用with-http_auth_request_module配置选项编译了NGINX开源。运行此命令并验证输出是否包括 --with-http_auth_request_module:
$ nginx -V 2>&1 | grep -- 'http_auth_request_module'
- 在需要请求身份验证的位置,指定auth_request指令,在该指令中指定将授权子请求转发到的内部位置:
location /private/ {
auth_request /auth;
#...
}
在这里,对于每个到 /private 的请求,都会向内部 /auth 位置发出一个子请求。
- 指定一个内部位置和此位置内的proxy_pass指令,该指令将把身份验证子请求代理到身份验证服务器或服务:
location = /auth {
internal;
proxy_pass http://auth-server;
#...
}
- 由于身份验证子请求将丢弃请求体,因此需要将proxy-pass-request-body指令设置为off,并将Content-Length头设置为空字符串:
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;
}
}
}
参考文档
https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-subrequest-authentication/