admin (empty)local 0.078125GB>
可以看到默认显示两个库,我们需要进入admin库进行权限设置(这个时候因为服务没有添加权限参数,所以默认是有权限进行相关设置的)
> use admin
switched to db admin
> db.addUser('sa','sa')
{
"user" : "sa",
"readOnly" : false,
"pwd" : "75692b1d11c072c6c79332e248c4f699",
"_id" : ObjectId("53af835ada88ac42a40917a0")
}
> db.system.users.find()
{ "_id" : ObjectId("53af835ada88ac42a40917a0"), "user" : "sa", "readOnly" : false, "pwd" : "75692b1d11c072c6c79332e248c4f699" }
二、我们关掉之前开启的服务,添加"--auth"权限参数,重新启动MongoDB服务
D:\>mongod --dbpath D:\mongodb\data --logpath=D:\mongodb\logs\mongodb.log --auth 我们再次连接并操作:
D:\>mongo
MongoDB shell version: 2.4.8
connecting to: test
> use admin
switched to db admin
> show collections
Sun Jun 29 11:17:27.103 error: {
"$err" : "not authorized for query on admin.system.namespaces",
"code" : 16550
} at src/mongo/shell/query.js:128
发现如果不加身份信息默认连接的话,是没有权限操作的。我们验证下之前添加的用户,再操作试下:
> db.auth('sa','sa')1 //返回1表示验证成功,返回0表示验证失败
> show collections
system.indexes
system.users
发现验证成功可以对admin库进行操作了,我们再连接其他库试试:
D:\>mongo
MongoDB shell version: 2.4.8connecting to: test> show collections
Sun Jun 29 11:20:17.996 error: { "$err" : "not authorized for query on test.system.namespaces", "code" : 16550} at src/mongo/shell/query.js:128> db.auth('sa','sa')
switched to db admin> db.auth('sa','sa')1> use test
switched to db test> show collections
三、添加完顶层admin用户,可以用admin账户进行其他用户的设置
如果想让单独的库有单独的用户名就得先从admin登录然后设置相应的用户信息,具体操作如下:
D:\>mongo
MongoDB shell version: 2.4.8connecting to: test> use admin
switched to db admin> db.auth('sa','sa')1 //先从admin登录> use test
switched to db test> show collections> db.addUser('test','test') //添加test库的用户{ "user" : "test", "readOnly" : false, "pwd" : "a6de521abefc2fed4f5876855a3484f5", "_id" : ObjectId("53af874c5017b6747e68da2a")
}
再次单独登录test试试:
D:\>mongo
MongoDB shell version: 2.4.8connecting to: test> show collections //未登录没有权限Sun Jun 29 11:27:52.899 error: { "$err" : "not authorized for query on test.system.namespaces", "code" : 16550} at src/mongo/shell/query.js:128> db.auth('test','test') //之前设置的账户1 //登录成功> show collections