MongoDB在2.4最新版本中对用户权限管理做了全新的调整,细化了权限,增强了安全性,越来越像mysql的权限管理了

 

权限规则:

1.  无密码启动mongodb服务

            在admin库创建的是超级用户,密码启动后,可查看全部数据库及数据表

            在自定义库(例如: test, mimvp_money库)创建的普通用户,仅可查看本库内的数据表

2.  密码启动mongodb服务

            admin超级用户,仅可在use admin选择库后,db.auth("sadmin", "sadmin")权限认证登陆,不仅可查看本库(admin)下的数据表,还可查看其它全部数据库(例如: test, mimvp_money库)下的数据表

             test普通用户,仅可在use test选择库后,db.auth("test", "test")权限认证登陆,仅可查看本库(test)下的数据表,不可查看admin或其它库(例如:mimvp_money库)下的数据表

3. 删除用户,仅在无密码启动mongodb服务后,登陆才可执行

 

1. 创建一个超级用户

方法1

use  admin
db.addUser("username", "password");​             
// 添加用户(可读可写)
db.addUser("username", "password", true);   // 添加用户(只读权限 readOnly-->true)

roles 权限如下:

Available roles:

  • read
  • readWrite
  • dbAdmin
  • userAdmin
  • clusterAdmin
  • readAnyDatabase
  • readWriteAnyDatabase
  • dbAdminAnyDatabase
  • userAdminAnyDatabase

 

示例: 

1. 无密码启动mongodb服务

先在 /etc/mongod.conf 配置文件里,注释掉 # auth=true

启动 /usr/bin/mongod -f /etc/mongod.conf

注: PHP 7 启动权限 启用用户权限:

security:
  authorization: enabled

2. 登陆mongo客户端

方式1:推荐,已弃用

db.addUser("sadmin","sadmin")

方式2:

db.createUser({user:"sadmin",pwd:"sadmin",roles:[{ role:"userAdminAnyDatabase", db:"admin" }],customData:{description:"superuser"}})

db.createUser({user:"money",pwd:"$xxxx",roles:[{role:"readWrite", db:"dbmoney"}],customData:{description:"db_rw"}})

> db.addUser("sadmin","sadmin")
WARNING: The 'addUser' shell helper is DEPRECATED. Please use 'createUser' instead
Successfully added user: { "user" : "sadmin", "roles" : [ "root" ] }
> 
> db.createUser({"user":"root","pwd":"root","roles":[]})
Successfully added user: { "user" : "root", "roles" : [ ] }
> db.system.users.find()
{ "_id" : "admin.sadmin", "user" : "sadmin", "db" : "admin", "credentials" : { "MONGODB-CR" : "8e698924f101b98694a0ce798b2fe76b" }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
{ "_id" : "admin.root", "user" : "root", "db" : "admin", "credentials" : { "MONGODB-CR" : "2a8025f0885adad5a8ce0044070032b3" }, "roles" : [ ] }

 

方法2:

use admin
db.createUser(
  {
    user: "adminUserName",
    pwd: "userPassword",
    roles:
    [
      {
        roles: "userAdminAnyDatabase",
        db: "admin"
      }
    ]
  }
)

超级用户的role有两种,userAdmin或者userAdminAnyDatabase(比前一种多加了对所有数据库的访问)。

db是指定数据库的名字,admin是管理数据库。

 

2. 用新创建的用户登录

mongo --host xxx -u adminUserName -p userPassword --auth enticationDatabase admin

 

3. 查看当前用户的权限

db.runCommand(
  {
    usersInfo:"userName",
    showPrivileges:true
  }
)

查看用户

use admin
db.system.users.find();

> db.system.users.find();
{ "_id" : "admin.root", "user" : "root", "db" : "admin", "credentials" : { "MONGODB-CR" : "2a8025f0885adad5a8ce0044070032b3" }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
{ "_id" : "test.test", "user" : "test", "db" : "test", "credentials" : { "MONGODB-CR" : "a6de521abefc2fed4f5876855a3484f5" }, "roles" : [ { "role" : "dbOwner", "db" : "test" } ] }
{ "_id" : "admin.sadmin", "user" : "sadmin", "db" : "admin", "credentials" : { "MONGODB-CR" : "8e698924f101b98694a0ce798b2fe76b" }, "roles" : [ ] }

 

4. 创建一般用户,也是用createUser

use db01
db.createUser(
  {
    user:"oneUser",
    pwd:"12345",
    roles:[
      {role:"read",db:"db01"},
      {role:"read",db:"db02"},
      {role:"read",db:"db03"}
    ]
  }
)

 

5. 创建一个不受访问限制的超级用户

use admin
db.createUser(
  {
    user:"superuser",
    pwd:"pwd",
    roles:["root"]
  }
)

 

6. 修改密码

use admin
db.changeUserPassword("username", "xxx")

 

7. 查看用户信息

db.runCommand({usersInfo:"userName"})

> db.runCommand({usersInfo:"sadmin"})
{
	"users" : [
		{
			"_id" : "admin.sadmin",
			"user" : "sadmin",
			"db" : "admin",
			"roles" : [
				{
					"role" : "root",
					"db" : "admin"
				}
			]
		}
	],
	"ok" : 1
}
> db.runCommand({usersInfo:"root"})
{
	"users" : [
		{
			"_id" : "admin.root",
			"user" : "root",
			"db" : "admin",
			"roles" : [ ]
		}
	],
	"ok" : 1
}

 

8. 修改密码和用户信息

db.runCommand(
  {
    updateUser:"username",
    pwd:"xxx",
    customData:{title:"xxx"}
  }
)

 

9. 删除用户

经验证:只在无密码启动mongodb服务后,才可删除用户权限

use admin;
db.system.users.
remove({user:"username"});

 

10. php客户端连接

方法1:

$mongo = new Mongo();  
$db = $mongo->selectDB('db_money');  	// 切换到tank数据库 
$db->authenticate("user", "123456");  		// 认证
 
$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://user:123456@127.0.0.1:27017/db_money");  // 认证用户,这里的数据库只启认证作用
$db = $mongo->selectDB('db_money'); 		// 真正选取数据库
 
$users= $db->selectCollection("users");
$cursor = $users->find();
foreach ($cursor as $id => $value) {
  	echo "$id: "; print_r($value); echo "<br>";
}

 

Python 连接Mongodb

MONGO_SERVER = {
                 "host"     :   "127.0.0.1",
                 "port"     :   27017,
                 "dbname"   :   "db_money",
                 "user"     :   "user",
                 "pwd"      :   "123456"
              }

def initial(self, mongo_server=MONGO_SERVER):
    try:
        self.host = mongo_server.get("host", "127.0.0.1")
        self.port = mongo_server.get("port", 27017)
        self.dbname = mongo_server.get("dbname", "local")
        self.user = mongo_server.get("user", "root")
        self.pwd = mongo_server.get("pwd", "123456")
        
#		# 无密码
#        self.conn = pymongo.Connection(self.host, self.port)
#        self.db = self.conn[self.dbname]
        
		# 有密码
        self.client = pymongo.MongoClient("%s:%d"%(self.host, self.port))
        self.client[self.dbname].authenticate(self.user, self.pwd, self.dbname, mechanism='MONGODB-CR')
        self.db = self.client[self.dbname]
        
    except Exception as ex:
        print("YGMongo initial error: " + str(ex))

 

注:

1. 和用户管理相关的操作基本都要在admin数据库下运行,要先use admin;

2. 如果在某个单一的数据库下,那只能对当前数据库的权限进行操作;

3. db.addUser是老版本的操作,现在版本也还能继续使用,创建出来的user是带有root role的超级管理员。

 

参考推荐:

浅析MongoDB用户管理