MongoDB 用户 权限 设置 详解
[root@localhost zhangy]# mongoMongoDB shell version: 2.4.6connecting to: tank> use admin //切换到admin数据库switched to db admin> show collections;system.indexessystem.users //用户表> db.system.users.find(); //用户表没有数据> db.addUser('tank','test'); //添加一个管理员账号{ "user" : "tank", "readOnly" : false, "pwd" : "988432606980d0695e4f668f6bbc643a", "_id" : ObjectId("529e5d543b6a4608ac833429")}
?三,开启动用户权限认证
[root@localhost zhangy]# vim /etc/mongodb.conf //将auth=true前面的注释拿掉[root@localhost zhangy]# /etc/init.d/mongod restart //重启生效
?四,用户只能在用户所在数据库登录,管理员需要通过admin认证后才能管理其他数据库
[root@localhost zhangy]# mongoMongoDB shell version: 2.4.6connecting to: tank> show dbs; //显示所有数据库失败,因为还没有认证Wed Dec 4 06:39:50.925 listDatabases failed:{ "ok" : 0, "errmsg" : "unauthorized" } at src/mongo/shell/mongo.js:46> db.auth('tank','test'); //认证失败,因为这个用户不属于tank这个数据库Error: 18 { code: 18, ok: 0.0, errmsg: "auth fails" }0> use admin //切换到admin数据库switched to db admin> db.auth('tank','test'); //在admin数据库认证成功1> use tank; //切换到tank数据库switched to db tank> show collections; //不会在提示没有权限了contactsystem.indexesusers
?五,添加普通用启
> use tank;switched to db tank> db.addUser('tank1','test'); //为tank数据库添加了一个可读写用户tank1{ "_id" : ObjectId("529e5f8474b4c660718a70f3"), "user" : "tank1", "readOnly" : false, "pwd" : "35dd47abff098f5b4f0b567db8edeac5"}> db.addUser('tank2','test',true); //为tank数据库添加了一个只读用户tank2{ "user" : "tank2", "readOnly" : true, "pwd" : "1792916c544d247538ded52e6df7b887", "_id" : ObjectId("529e67553992b24438d5e315")}> exit //退出bye[root@localhost zhangy]# mongoMongoDB shell version: 2.4.6connecting to: tank> db.auth('tank1','test'); //刚添加的用户可以登录。1
?六,php客户端连接1, 推荐方法一
$mongo = new Mongo(); $db = $mongo->selectDB('tank'); //切换到tank数据库 $db->authenticate("tank3", "test"); //认证$users= $db->selectCollection("users"); //选取users表$cursor = $users->find(); //读取数据foreach ($cursor as $id => $value) { echo "$id: "; print_r($value); echo "<br>";}
?这种方式比较好理解,根命令行下的操作过程差不多。2,推荐方法二
$mongo = new Mongo("mongodb://tank3:test@127.0.0.1:27017/tank"); //认证用户,这里的数据库,只启认证作用$db = $mongo->selectDB('tank'); //选取数据库$users= $db->selectCollection("users");$cursor = $users->find();foreach ($cursor as $id => $value) { echo "$id: "; print_r($value); echo "<br>";}
?上面二种方法的不同在于,一个先选数据库在认证,一个先认证在选数据库。