LDAP认证仅MongoDB Enterprise支持,社区版完全不支持;必须配置TLS加密通信;ldap.bindQueryUser为查询代理账号而非管理员;客户端须用PLAIN机制并传完整DN或按规则映射。

LDAP 认证在 MongoDB 中必须用 Enterprise 版
MongoDB 社区版完全不支持 LDAP 认证,连配置入口都没有。你看到的 ldap 相关参数(比如 ldap.bindQueryUser、ldap.transportSecurity)在社区版启动时会被忽略,且不会报错——这最容易让人误以为“配置生效了”。只有 MongoDB Enterprise(含 Atlas 企业版部署)才内置 LDAP 客户端逻辑,能发起 Bind 和 Search 请求。
常见错误现象:db.runCommand({connectionStatus: 1}) 返回的 authenticationMechanisms 里没有 PLAIN 或 SCRAM-SHA-256 以外的机制;日志里查不到 LDAP bind request 类记录;用 mongosh --username "cn=user,dc=example,dc=com" --authenticationMechanism=PLAIN 连接直接提示 Authentication failed,但没说明是机制不支持还是凭据错。
- 确认版本:运行
mongod --version,输出中必须含Enterprise字样 - 不要尝试打补丁或编译社区版加 LDAP 支持——底层依赖的 SASL 库(如 OpenLDAP + Cyrus SASL)和认证流程由 Enterprise 专有模块控制
- Atlas 用户注意:仅限
Advanced及以上订阅层级支持 LDAP 集成,且需在 Organization 级开启,Project 级无法单独配置
配置 mongod 启用 LDAP 转发前必须设好 TLS
MongoDB Enterprise 强制要求 LDAP 通信加密,不接受 ldap.transportSecurity: none。哪怕你的 LDAP 服务跑在 localhost,也必须配 ldaps:// 或启用 StartTLS(对应 ldap.transportSecurity: tls)。否则服务根本起不来,日志里会卡在 Failed to initialize LDAP client: LDAP server URI is invalid。
使用场景:内网环境常有人想省事用明文 LDAP,但 MongoDB 不让。你得先让 LDAP 服务支持 LDAPS(443/636 端口)或配置 StartTLS(389 端口 + TLS 升级),再同步配置 MongoDB 的证书信任链。
-
ldap.uri必须以ldaps://开头,或设为ldap://host:389+ldap.transportSecurity: tls -
ldap.tlsCAFile指向 LDAP 服务器证书的根 CA 文件(不是自签证书本身),MongoDB 用它校验 LDAPS 证书有效性 - 若 LDAP 用自签名证书,别改
ldap.tlsAllowInvalidCertificates—— 这个参数只影响 MongoDB 自身对外 HTTPS 请求,对 LDAP 连接无效
ldap.bindQueryUser 和 ldap.bindQueryPassword 不是“管理员账号”,而是查询代理身份
这两个配置项填的是 MongoDB 用来搜索用户 DN 的“查询账号”,不是最终登录用户的账号密码。它的权限只需能执行 search(比如 cn=readonly,dc=example,dc=com),不需要 bind 权限。很多人误填成域管理员账号,结果日志里反复出现 LDAP bind failed: Invalid credentials,其实是这个查询账号密码错了,跟终端用户完全无关。
参数差异:ldap.bindQueryUser 是完整 DN(如 uid=ldap-search,ou=service,dc=example,dc=com),不能简写为用户名;ldap.bindQueryPassword 是明文密码(MongoDB 不支持密钥文件或 KMS 加密存储)。
- 验证方法:用命令行工具模拟查询:
ldapsearch -x -H ldaps://ldap.example.com -D "uid=ldap-search,ou=service,dc=example,dc=com" -W -b "dc=example,dc=com" "(uid=john)" dn - 如果 LDAP 目录结构分多 OU(如 users / groups),
ldap.userToDNMapping必须显式定义映射规则,否则 MongoDB 默认只查ou=people下的条目 - 避免硬编码密码:把
ldap.bindQueryPassword放进配置文件风险高,建议用mongod --config /etc/mongod.conf --setParameter ldapBindQueryPassword=xxx启动时传入(仍非最佳实践,但比落盘好)
客户端连接时必须用 PLAIN 机制,且用户名是完整 DN 或映射后字符串
MongoDB 不支持用 userPrincipalName(如 john@example.com)直连。你得按 ldap.userToDNMapping 规则把登录名转成 DN,或者让 LDAP 服务本身支持 rfc2307 式的 uid 查找。否则 mongosh --username john --password xxx --authenticationMechanism=PLAIN 一定失败,错误信息是模糊的 Authentication failed,实际原因是 MongoDB 根本没找到对应 DN。
性能影响:每次认证都会触发一次 LDAP Search + Bind,比本地 SCRAM 快不了多少;若 LDAP 延迟高(>100ms),连接建立会明显卡顿,且无连接池复用。
- 最简映射示例:
ldap.userToDNMapping: '{ "pattern" : "([^@]+)@example\.com", "replacement" : "uid=$1,ou=users,dc=example,dc=com" }',这样--username john@example.com才能正确转成 DN - 务必测试
db.runCommand({saslStart: 1, mechanism: "PLAIN", payload: BinData(0, "AGpvaG4AaG9tZXBhc3M=")})(Base64 编码的
