MongoDB_3.0.4安全认证
官方文档:https://docs.mongodb.org/manual/reference/method/js-user-management/
1.关闭认证(不使用 –auth参数),启动 mongoDB

启动Mongo
/home/nbsl/mongodb-linux-x86_64-3.0.4/bin/mongod –config /home/nbsl/mongodb-linux-x86_64-3.0.4/mongodb.cnf
2.连接Mongo
cd /home/nbsl/mongodb-linux-x86_64-3.0.4/bin
./mongo
注意3.0版本之后,mongodb加入了SCRAM-SHA-1校验方式,直接使用MongoVUE或者roboMongo等客户端工具直接将无法成功连接,查看日志文件会发现如下错误
authenticate db: userdb { authenticate: 1, nonce: “xxx”, user: “myuser”, key: “xxx” } 2015-06-02T09:57:18.877+0800 I ACCESS [conn2] Failed to authenticate myuser@userdb with mechanism MONGODB-CR: AuthenticationFailed MONGODB-CR credentials missing in the user document 下面给出具体解决办法:
首先关闭认证,修改system.version文档里面的authSchema版本为3,初始安装时候应该是5,命令行如下: > use admin switched to db admin > var schema = db.system.version.findOne({“_id” : “authSchema”}) > schema.currentVersion = 3 3 > db.system.version.save(schema) WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })不过如果你现在开启认证,仍然会提示AuthenticationFailed MONGODB-CR credentials missing in the user document 原因是原来创建的用户已经使用了SCRAM-SHA-1认证方式 解决方式就是删除刚刚创建的用户,重建即可: > use userdb switched to db userdb > db.dropUser(“myuser”) true >db.createUser({user:’myuser’,pwd:’123456′,roles:[{role:’dbOwner’,db:’userdb’}]}) |
3.创建超级用户
use admin
1 2 3 4 5 6 7 |
db.createUser( { user:"superuser", pwd:"passw0rd", roles:["root"] } ) |
4.关闭Mongo
db.shutdownServer()
千万不要 kill -9 pid,kill -9 将有可能导致数据库损坏,必要时可使用 kill -15 pid
5.开启认证(使用 –auth参数),启动 mongoDB

启动Mongo
/home/nbsl/mongodb-linux-x86_64-3.0.4/bin/mongod –config /home/nbsl/mongodb-linux-x86_64-3.0.4/mongodb.cnf
6.连接Mongo
./mongo
use admin
show collections
Error: not authorized on YG to execute command { usersInfo: 1.0 }
db.auth(‘superuser’,’passw0rd’)
show collections
show users
7.给数据库YG添加普通用户读写权限
1 2 3 4 5 6 7 8 9 10 |
use YG db.createUser( { user:"yguser", pwd:"1qaz2wsx", roles:[ {role:"readWrite",db:"yg"} ] } ) |
创建完毕,验证一下:
db.auth(‘yguser’,’1qaz2wsx’)
show collections
8.查看Mongo所有用户
use admin
db.auth(‘superuser’,’passw0rd’)
db.system.users.find()
其他命令
>删除用户:
use YG
db.dropUser(“yguser”)
>授予角色:
db.grantRolesToUser( “yguser” , [ { role: “dbOwner”, db: “YG” } ])
>取消角色:
db.revokeRolesFromUser( “yguser” , [ { role: “readWrite”, db: “YG” } ])