Để tạo người dùng mới trong MongoDB với quyền kiểm soát truy cập (RBAC), bạn dùng phương thức db.createUser() trên database mục tiêu. Cần chỉ định: username, password, roles (vai trò), và cơ chế xác thực (mechanism).
1. Tạo user "John" với role readWrite trên database "test"
> db.createUser({
user: "John",
pwd: "123456", // Mật khẩu (nên dùng mạnh hơn trong production)
roles: [
{ role: "readWrite", db: "test" } // Quyền đọc/ghi trên database test
],
mechanisms: ["SCRAM-SHA-256"] // Cơ chế xác thực mặc định MongoDB 4.0+
});
2. Kết quả thành công
Successfully added user: {
"user": "John",
"roles": [{ "role": "readWrite", "db": "test" }],
"mechanisms": ["SCRAM-SHA-256"]
}
3. Xem danh sách user hiện có
> db.getUsers();
Kết quả:
[
{
"_id": "test.John",
"user": "John",
"db": "test",
"roles": [{ "role": "readWrite", "db": "test" }],
"mechanisms": ["SCRAM-SHA-256"]
}
]
Các Role phổ biến:
read: Chỉ đọc.readWrite: Đọc + ghi.dbAdmin: Quản trị DB (tạo index, collection, stats...).userAdmin: Quản trị user/role.dbOwner: Toàn quyền trên DB (readWrite + dbAdmin + userAdmin).- Cluster-level:
clusterAdmin,hostManager,backup/restore.
Best Practice:
- Tuân thủ nguyên tắc **Least Privilege** (quyền tối thiểu).
- Dùng mật khẩu mạnh, xoay vòng định kỳ.
- Tạo user trên database `admin` cho quản trị cluster.
- Bật authentication:
mongod --auth.