你忘--auth使
創建用戶
// ensure that we have new db, no roles, no users
use products
db.dropDatabase()
// create admin user
use products
db.createUser({
"user": "prod-admin",
"pwd": "prod-admin",
"roles": [
{"role": "clusterAdmin", "db": "admin" },
{"role": "readAnyDatabase", "db": "admin" },
"readWrite"
]},
{ "w": "majority" , "wtimeout": 5000 }
)
// login via admin acont in order to create readonly user
// mongo --username=prod-admin --password=prod-admin products
db.createUser({
"user": "prod-r",
"pwd": "prod-r",
"roles": ["read"]
})
啓用身份驗證:
sudo vim /etc/mongod.conf # edit file
# Turn on/off security. Off is currently the default
#noauth = true
auth = true
sudo service mongod restart # reload configuiration
檢查寫入限制:
# check if write operation for readonly user
$ mongo --username=prod-r --password=prod-r products
MongoDB shell version: 2.6.4
connecting to: products
> db.laptop.insert({"name": "HP"})
WriteResult({
"writeError" : {
"code" : 13,
"errmsg" : "not authorized on products to execute command { insert: \"laptop\", documents: [ { _id: ObjectId('53ecb7115f0bfc61d8b1113e'), name: \"HP\" } ], ordered: true }"
}
})
# check write operation for admin user
$ mongo --username=prod-admin --password=prod-admin products
MongoDB shell version: 2.6.4
connecting to: products
> db.laptop.insert({"name": "HP"})
WriteResult({ "nInserted" : 1 })
# check read operation for readonly user
$ mongo --username=prod-r --password=prod-r products
MongoDB shell version: 2.6.4
connecting to: products
> db.laptop.findOne()
{ "_id" : ObjectId("53ecb54798da304f99625d05"), "name" : "HP" }
你能否也請發送你如何連接? –
您是否在'admin'數據庫中創建了[管理用戶](http://docs.mongodb.org/manual/tutorial/add-user-administrator/)?如果'admin'數據庫中沒有用戶,您仍然可以通過[localhost exception]進行連接(http://docs.mongodb.org/manual/tutorial/add-user-administrator/#authenticate-with-全行政存取通本地主機)。當'mongod'啓用auth啓用時,localhost異常可用於設置您的第一個管理用戶。 – Stennie
感謝Stennie的回覆。我做了以下事情//創建管理員用戶 使用管理員 db.addUser('root','strong_password'); //只讀用戶 使用dbforuser1 db.addUser('user1','user1_pass',true); 當以user1登錄時,它仍然允許我寫入。請提供幫助。 – user3111436