MongoDB数据库用户角色与权限管理

查看数据库

使用终端命令行输入 mongo 登陆 mongodb 之后切换到 admin 库,并认证后可查看所有数据库,操作如下所示:

[root@renwole.com ~]# mongo
MongoDB shell version v4.4.0
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("1ea1-4343-9523-167a101973a9") }
MongoDB server version: 4.4.0
> use admin
> db.auth("admin","InaM6Aip#2JBlWwY")
1
> show dbs
admin      0.000GB
config     0.000GB
local      0.000GB

说明:1 表示认证成功,0 表示认证失败,认证失败后查看数据库无任何返回。

创建数据库及用户

创建一个 renwoledb 数据库并授权 renwole 用户为该库的 dbOwner 角色。另外、MongoDB数据库实行注册制,数据库内无内容时,无法查看到新建的数据库,操作如下:

> use renwoledb
> db.createUser(
        {
            user:"renwole",
            pwd:"renwolecom",
            roles:[{role:"dbOwner",db:"renwoledb"}]
        }
)

此时已完成了一库一账号的创建。如果创建用户提示无权限,请先使用超级管理员登录之后切换到对应的数据库再创建即可,如下所示:

MongoDB shell version v4.4.0
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("7be9-4c30-ad2e-2a5b58127ab7") }
MongoDB server version: 4.4.0
> use renwoledb
switched to db renwoledb
> db.createUser(
         {
             user:"renwole",
             pwd:"renwolecom",
             roles:[{role:"dbOwner",db:"renwoledb"}]
         }
 )
uncaught exception: Error: couldn't add user: command createUser requires authentication :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.createUser@src/mongo/shell/db.js:1343:11
@(shell):1:1

> use admin
switched to db admin
> db.auth("root","renwolecompassword")
1
> use renwoledb
switched to db renwoledb
> db.createUser(
         {
             user:"renwole",
             pwd:"renwolecom",
             roles:[{role:"dbOwner",db:"renwoledb"}]
         }
 )
Successfully added user: {
	"user" : "renwole",
	"roles" : [
		{
			"role" : "dbOwner",
			"db" : "renwoledb"
		}
	]
}

添加 root 用户,拥有整个 MongoDB 最高权限,建议取消认证模式后,先进入到 admin 库,再添加 root 用户权限

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

密码修改

修改某个账号的数据库密码需要进入到该数据库,认证后再修改,否则报错,操作如下:

> use renwoledb
> db.changeUserPassword("renwole", "renwolecompwdnew")
> db.auth("renwole","renwolecompwdnew")
1

删除用户及数据库

删除用户(必须切换到admin使用最高权限删除某个用户角色)
> db.system.users.remove({user:"renwole"});
WriteResult({ "nRemoved" : 1 })

删除所有用户(必须具备超级管理权限才能删除)
> db.system.users.remove({})

删除数据库(必须切换到指定的数据库,然后再删除)
> use renwoledb
switched to db renwoledb
> db.dropDatabase()
{ "ok" : 1 }
>

你可能还需要查看 《MongoDB 基本常用管理命令详解
参阅:https://www.cnblogs.com/pl-boke/p/10063351.html

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Captcha Code