--auth 啟用。admin 資料庫為特權庫:admin.system.users 為空時,即使 --auth 也可無認證操作;一旦添加用戶,認證即生效。--auth 下仍可匿名連接,但無任何操作權限。admin 庫用戶可管理所有庫;其他庫用戶僅限本庫。readOnly/readWrite。| 角色 | 權限範圍 | 關鍵動作示例 |
|---|---|---|
| read | 單庫唯讀 | find, aggregate, count, distinct, mapReduce (inline) |
| readWrite | 單庫讀寫 | read 所有 + insert, update, remove, createIndex, dropCollection |
| dbAdmin | 單庫管理 | createCollection, dropIndex, compact, repairDatabase, stats |
| userAdmin | 單庫用戶管理 | createUser, dropUser, grantRole, changePassword |
| clusterAdmin | 叢集管理 | replSet*, sharding*, addShard, shutdown, logRotate |
| readAnyDatabase | 所有庫唯讀 | 同 read,跨庫 |
| readWriteAnyDatabase | 所有庫讀寫 | 同 readWrite,跨庫 |
| userAdminAnyDatabase | 所有庫用戶管理 | 同 userAdmin,跨庫 |
| dbAdminAnyDatabase | 所有庫管理 | 同 dbAdmin,跨庫 |
root 角色 (僅 admin) 擁有所有權限。
--auth 啟用認證。--nohttpinterface 關閉 28017 HTTP 介面 (預設開啟,風險大)。--bind_ip 127.0.0.1 或內網 IP,限制訪問來源。--port 修改預設 27017 (降低自動掃描風險)。use admin
db.addUser("admin", "strongpass") // 超管
use mydb
db.addUser("appuser", "apppass") // 讀寫
db.addUser("readonly", "pass", true) // 唯讀
use admin
db.createUser({
user: "admin", pwd: "strongpass",
roles: ["root"]
})
// 為應用建立跨庫角色用戶
db.createUser({
user: "appuser", pwd: "apppass",
roles: [
{ role: "readWrite", db: "mydb" },
{ role: "read", db: "mydb_log" }
]
})
--auth 並建立 admin 管理員。--bind_ip) 或防火牆限制。--nohttpinterface)。# 安裝為服務 (Windows)
mongod --dbpath d:\data --logpath d:\log\mongo.log --auth --nohttpinterface --install
# 連接並認證
mongo mydb -u admin -p strongpass
# 或連接後
db.auth("user", "pass")
# 查看用戶
db.system.users.find()
show dbs
use mydb