1. 程式人生 > 資料庫 >MongoDB資料庫使用者角色和許可權管理詳解

MongoDB資料庫使用者角色和許可權管理詳解

檢視資料庫

使用終端命令列輸入 mongo 登陸 mongodb 之後切換到 admin 庫,並認證後可檢視所有資料庫,操作如下所示:

[[email protected] ~]# 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",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",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資料庫使用者角色和許可權管理的文章就介紹到這了,更多相關MongoDB使用者角色和許可權管理內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!