Nginx本身不支持直接LDAP认证,必须通过auth_request模块代理至nginx-ldap-auth守护进程实现;该方案分三层协作:Nginx拦截请求、Python守护进程执行LDAP Bind验证、LDAP服务器提供目录服务。

Nginx 本身不支持直接对接 LDAP,auth_basic 只能读取本地 .htpasswd 文件,无法完成 LDAP 查询验证。要实现企业级统一认证,必须借助外部组件——最常用、轻量且生产就绪的方案是 nginx-ldap-auth,它通过 Nginx 的 auth_request 模块将认证逻辑“代理”出去。
为什么不能只用 auth_basic 做 LDAP 认证
auth_basic 是 HTTP 协议层的静态基础认证机制,仅负责弹出登录框、解析 Base64 编码的用户名密码,并比对本地文件。它不具备以下能力:
- 连接 LDAP 服务器(如 OpenLDAP 或 Active Directory)
- 执行 Bind 操作验证凭据
- 按 BaseDN 和 Filter 搜索用户条目
- 处理 TLS/STARTTLS 加密通信
- 返回动态的用户属性(如邮箱、部门)供后续使用
核心架构:Nginx + auth_request + nginx-ldap-auth-daemon
整个流程分三层协作:
-
Nginx 层:拦截请求,对目标路径(如
/admin/或/api/)发起auth_request子请求到本地守护进程 -
Python 守护进程层(
nginx-ldap-auth-daemon.py):接收子请求,提取头中传递的用户名/密码,连接 LDAP 服务器完成 Bind 验证,返回 200(成功)或 401(失败) - LDAP 目录层:提供标准 LDAPv3 接口,支持 SSL/TLS 加密和复杂 ACL 控制
关键配置步骤
1. 确保 Nginx 启用 auth_request 模块
运行 nginx -V 2>&1 | grep -o with-http_auth_request_module,若无输出需重新编译或换用发行版预编译包(如 Ubuntu 的 nginx-extras)。
2. 部署并启动 nginx-ldap-auth 守护进程
从官方仓库克隆项目,安装 python3-ldap,按需修改 nginx-ldap-auth.conf 中的 LDAP 参数:
-
X-Ldap-URL:如ldaps://ad.example.com或ldap://ldap.internal:389 -
X-Ldap-BindDN:绑定账号,如cn=admin,dc=example,dc=com -
X-Ldap-BindPass:绑定密码(建议用环境变量或文件方式注入,避免硬编码) -
X-Ldap-BaseDN:用户搜索根,如ou=People,dc=example,dc=com -
X-Ldap-SearchFilter:过滤模板,如(uid=%s)或(sAMAccountName=%s)
启动守护进程:./nginx-ldap-auth-daemon-ctl.sh start,默认监听 http://127.0.0.1:8888/auth。
3. 在 Nginx 配置中启用代理认证
在 location 块中添加:
location ^~ /admin/ {
auth_request /auth-proxy;
auth_request_set $user $upstream_http_x-auth-user;
proxy_set_header X-User $user;
proxy_pass http://backend_app;
}
location = /auth-proxy {
internal;
proxy_pass http://127.0.0.1:8888/auth;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header X-Original-URI $request_uri;
}
说明:
-
auth_request /auth-proxy触发子请求;internal确保该路径不可被外部直接访问 -
auth_request_set提取守护进程返回的响应头(如X-Auth-User),存入变量供下游使用 -
proxy_set_header X-User把认证后的用户名透传给后端应用,实现单点登录上下文
安全与运维要点
HTTPS 强制启用:所有客户端访问必须走 HTTPS,否则用户名密码在 auth_request 子请求中仍以明文形式暴露在内网链路(虽比公网好,但不符合等保要求)。
守护进程权限隔离:用非 root 用户运行 nginx-ldap-auth-daemon,禁用 shell 权限,配置 systemd 服务限制资源(CPU/Memory)。
LDAP 连接加固:务必启用 ldaps:// 或配置 STARTTLS;禁用匿名 Bind;定期轮换 BindDN 密码;在防火墙层面限制 LDAP 服务器仅允许 Nginx 主机访问。
日志与审计:开启守护进程的详细日志(DEBUG 级别),记录认证成功/失败、用户 DN、IP 地址;Nginx access log 中可加入 $upstream_http_x-auth-result 等自定义字段。


















