MongoDB 用户管理
讲解 MongoDB 基于角色的访问控制(RBAC)完整流程:连接实例、切换认证库、createUser 授权、db.auth 校验、启用 security.authorization 配置、带凭据登录与 dropUser 删除用户。
学完这一章,你能够
- 讲解 MongoDB 基于角色的访问控制(RBAC)完整流程:连接实例、切换认证库、createUser 授权、db.auth 校验、启用 security.authorization 配置、带凭据登录与 dropUser 删除用户。
用户管理流程与连接、切库、建用户
MongoDB 的安全治理核心是基于角色的访问控制(RBAC),涵盖创建用户、按库分配角色、验证凭据、开启服务端强制鉴权与吊销账号等环节。实际运维既可通过交互终端 `mongosh`(历史版 `mongo`)脚本化完成,也可借助 MongoDB Compass 界面辅助管理。
第一步在终端使用 `mongosh --host <hostname> --port <port>` 连接实例,其中 `--host` 指定主机名或 IP(如 `localhost` 或 `127.0.0.1`),`--port` 指定端口(默认 `27017`)。第二步通过 `use <database_name>` 切换到目标认证数据库——MongoDB 的用户账号始终归属于创建时所在的数据库(即认证库 `authenticationDatabase`),随后再由其 `roles` 数组声明可访问哪些库及何种角色。
第三步调用 `db.createUser({ user: "testuser", pwd: "password123", roles: [{ role: "readWrite", db: "<database_name>" }, { role: "dbAdmin", db: "<database_name>" }] })` 创建账号并授予读写(`readWrite`)与库管理(`dbAdmin`)角色(生产环境建议使用 `passwordPrompt()` 避免明文密码落入 Shell 历史)。第四步可立即在当前库执行 `db.auth("testuser", "password123")` 校验用户名与密码是否匹配。
启用强制鉴权、凭据登录与删除用户
第五步在配置文件 `mongod.conf` 中添加 `security:` 下级项 `authorization: "enabled"` 并重启 `mongod` 服务,使访问控制真正生效——未启用前即便创建了用户,匿名连接仍不受拦截。第六步启用后须携带身份参数登录:`mongosh --host <hostname> --port <port> -u "testuser" -p "password123" --authenticationDatabase "<database_name>"`。第七步不再需要某账号时,切至其所属认证库运行 `db.dropUser("testuser")` 即可彻底移除用户。
端到端用户生命周期实操演示
将上述步骤串联为完整演练:先用 `mongosh --host localhost --port 27017` 连入本机并 `use testdb`,在 `testdb` 中为 `testuser` 分配 `readWrite` 角色;接着向 `mongod.conf` 写入 `security.authorization: "enabled"` 并执行 `sudo systemctl restart mongod` 重启守护进程;再以 `-u "testuser" -p "password123" --authenticationDatabase "testdb"` 认证登录验证;最后运行 `db.dropUser("testuser")` 清理演示账号。本站离线 RBAC 验证器完整复现了该全周期及跨库越权拦截。
运行 mongosh 认证参数解析、createUser RBAC 鉴权、security.authorization 门禁及 dropUser 验证
"""Offline MongoDB user management, RBAC roles, auth & security.authorization verifier (Ch09 user)."""
import hashlib
import json
VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"
ROLE_PRIVILEGES = {
"read": {"find"},
"readWrite": {"find", "insert", "update", "delete"},
"dbAdmin": {"createIndex", "dropCollection", "collStats", "renameCollection"},
"dbOwner": {"find", "insert", "update", "delete", "createIndex", "dropCollection", "createUser"},
}
class OfflineAuthServer:
def __init__(self):
self.authorization_enabled = False
self.users = {} # (auth_db, username) -> {"pwd_hash": ..., "roles": [...]}
@staticmethod
def _hash_pwd(user: str, pwd: str) -> str:
return hashlib.sha256(f"{user}:{pwd}".encode("utf-8")).hexdigest()
def create_user(self, auth_db: str, user: str, pwd: str, roles: list):
self.users[(auth_db, user)] = {
"pwd_hash": self._hash_pwd(user, pwd),
"roles": list(roles),
}
return {"ok": 1}
def auth(self, auth_db: str, user: str, pwd: str) -> int:
rec = self.users.get((auth_db, user))
if not rec or rec["pwd_hash"] != self._hash_pwd(user, pwd):
return 0
return 1
def check_permission(self, auth_db: str, user: str | None, target_db: str, action: str) -> bool:
if not self.authorization_enabled:
return True
if user is None or (auth_db, user) not in self.users:
return False
for role_spec in self.users[(auth_db, user)]["roles"]:
if role_spec["db"] == target_db and action in ROLE_PRIVILEGES.get(role_spec["role"], set()):
return True
return False
def drop_user(self, auth_db: str, user: str) -> bool:
return self.users.pop((auth_db, user), None) is not None
def case_mongosh_host_port_auth_cli():
argv = [
"mongosh",
"--host",
"localhost",
"--port",
"27017",
"-u",
"testuser",
"-p",
"password123",
"--authenticationDatabase",
"testdb",
]
parsed = {
"host": argv[argv.index("--host") + 1],
"port": int(argv[argv.index("--port") + 1]),
"user": argv[argv.index("-u") + 1],
"auth_db": argv[argv.index("--authenticationDatabase") + 1],
}
expected = {"host": "localhost", "port": 27017, "user": "testuser", "auth_db": "testdb"}
return {
"name": "mongosh_host_port_auth_cli",
"summary": "解析 mongosh --host/--port/-u/-p/--authenticationDatabase 认证连接命令行参数。",
"expected": expected,
"actual": parsed,
"passed": parsed == expected,
}
def case_create_user_and_rbac_roles():
srv = OfflineAuthServer()
srv.authorization_enabled = True
res = srv.create_user(
"testdb",
"testuser",
"password123",
[
{"role": "readWrite", "db": "testdb"},
{"role": "dbAdmin", "db": "testdb"},
],
)
actual = {
"create_ok": res["ok"] == 1,
"can_insert_testdb": srv.check_permission("testdb", "testuser", "testdb", "insert"),
"can_create_index_testdb": srv.check_permission("testdb", "testuser", "testdb", "createIndex"),
"denied_other_db": not srv.check_permission("testdb", "testuser", "prod_db", "find"),
}
expected = {
"create_ok": True,
"can_insert_testdb": True,
"can_create_index_testdb": True,
"denied_other_db": True,
}
return {
"name": "create_user_and_rbac_roles",
"summary": "验证 db.createUser 分配 readWrite 与 dbAdmin 角色后的本库授权与跨库隔离拦截。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_auth_and_security_authorization_config():
conf = "security:\n authorization: \"enabled\"\n"
enabled = 'authorization: "enabled"' in conf
srv = OfflineAuthServer()
srv.create_user("testdb", "testuser", "password123", [{"role": "readWrite", "db": "testdb"}])
anon_before = srv.check_permission("testdb", None, "testdb", "find")
srv.authorization_enabled = enabled
anon_after = srv.check_permission("testdb", None, "testdb", "find")
good_auth = srv.auth("testdb", "testuser", "password123")
bad_auth = srv.auth("testdb", "testuser", "wrongpwd")
actual = {
"anon_allowed_before_enable": anon_before,
"anon_blocked_after_enable": not anon_after,
"good_auth_result": good_auth,
"bad_auth_result": bad_auth,
}
expected = {
"anon_allowed_before_enable": True,
"anon_blocked_after_enable": True,
"good_auth_result": 1,
"bad_auth_result": 0,
}
return {
"name": "auth_and_security_authorization_config",
"summary": "验证 security.authorization: enabled 生效前后匿名访问拦截与 db.auth 凭据校验。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_drop_user_and_relogin_rejection():
srv = OfflineAuthServer()
srv.authorization_enabled = True
srv.create_user("testdb", "testuser", "password123", [{"role": "readWrite", "db": "testdb"}])
auth_before = srv.auth("testdb", "testuser", "password123")
dropped = srv.drop_user("testdb", "testuser")
auth_after = srv.auth("testdb", "testuser", "password123")
can_read_after = srv.check_permission("testdb", "testuser", "testdb", "find")
actual = {
"auth_before": auth_before,
"dropped": dropped,
"auth_after": auth_after,
"can_read_after": can_read_after,
}
expected = {"auth_before": 1, "dropped": True, "auth_after": 0, "can_read_after": False}
return {
"name": "drop_user_and_relogin_rejection",
"summary": "验证 db.dropUser 删除用户后无法再次认证且操作权限立即失效。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_mongosh_host_port_auth_cli(),
case_create_user_and_rbac_roles(),
case_auth_and_security_authorization_config(),
case_drop_user_and_relogin_rejection(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 验证 --authenticationDatabase 解析、readWrite/dbAdmin 本库授权与跨库拦截、开启鉴权后匿名拒绝与删用户失效。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:74feac69002d259b709589ecc51a2de6912c81a57e0b47fa2bfe28d6f5220ae8
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:441906ae0c1941280b8e6abdf0e18687624d62a86af0ef18d25ded1c95aeaef0
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 `testdb` 中创建用户后,若登录时省略 `--authenticationDatabase "testdb"` 通常为什么会认证失败?
展开参考解答
客户端默认会尝试在 `admin` 库(或 URI 中指定的默认库)校验凭据;如果用户文档实际存放在 `testdb`,就必须通过 `--authenticationDatabase` 或 URI 的 `authSource=testdb` 指明认证库。