MongoDB4.28開啓權限認證(用戶密碼登錄)

MongoDB默認不啓用授權認證,只要能連接到該服務器,就可連接到mongod。若要啓用安全認證,需要更改配置文件mongdb.conf中的參數auth。

MongoDB的用戶是跟數據庫相關聯的,具體的數據庫,需要有對應的用戶,超級管理員也不能操作其他數據庫的。

MongoDB存儲所有的用戶信息在admin 數據庫的集合system.users中,保存用戶名、密碼和數據庫信息。


MongoDB開啓權限認證:配置用戶名和密碼認證登錄,操作步驟:

1、查看是否開啓認證登錄

$cd /usr/local/mongodb/bin

$cat mongodb.conf

#數據文件存放目錄

dbpath = /usr/local/mongodb/data

#日誌文件存放目錄

logpath = /usr/local/mongodb/logs/mongodb.log

logappend=true

#端口

port = 27017

#以守護程序的方式啓用,即在後臺運行

fork = true

#認證模式(true代表開啓認證登錄,false代表未開啓認證登錄)

auth=false   

#遠程連接

bind_ip=0.0.0.0

2、開啓用戶名和密碼認證(創建用戶均需進入admin數據庫)

2.1、爲admin數據庫創建管理員賬號

1、數據庫admin創建管理員賬號

[root@hadoop-master bin]# mongo

> use admin

> db.createUser({user:"root",pwd:"lianshi",roles:["root"]})

2、查看目前用戶

> show users

2.2、爲數據庫mytest創建普通用戶

1、給數據庫mytest創建cg用戶

>use mytest

> db.createUser({user:"cg",pwd:"lianshi",roles:[{role:"readWrite",db:"mytest"}]})

2、查看目前用戶

> show users

>db.system.users.find()命令可以查看創建的用戶

 

2.3、配置文件開啓用戶名密碼認證

#認證模式(true代表開啓認證登錄,false代表未開啓認證登錄)

auth=true

3、重啓mongo服務

[root@hadoop-master bin]# ps -ef |grep mongo

[root@hadoop-master bin]# kill -9 15231

$./mongod -f mongodb.conf

4、mongo授權訪問

4.1、admin數據庫授權登錄

1、mongo訪問

[root@hadoop-master bin]# mongo

> use admin

switched to db admin

> show users

2020-06-21T20:14:59.735+0800 E  QUERY    [js] uncaught exception: Error: command usersInfo requires authentication :

_getErrorWithCode@src/mongo/shell/utils.js:25:13

DB.prototype.getUsers@src/mongo/shell/db.js:1638:15

shellHelper.show@src/mongo/shell/utils.js:883:9

shellHelper@src/mongo/shell/utils.js:790:15

@(shellhelp2):1:1 -->授權配置並重啓後,此時查看用戶,會發現沒有權限

2、用用戶和密碼登錄

> db.auth("root","lianshi")

1

--->使用db.auth(root,lianshi)啓用auth認證,看到返回的值爲1,這就表示啓動成功了,然後我們再使用命令查看用戶和數據庫

4.1、mytest數據庫授權登錄

1、mongo訪問

> use mytest;

switched to db mytest

> show users

2020-06-21T21:25:41.293+0800 E  QUERY    [js] uncaught exception: Error: command usersInfo requires authentication :

_getErrorWithCode@src/mongo/shell/utils.js:25:13

DB.prototype.getUsers@src/mongo/shell/db.js:1638:15

shellHelper.show@src/mongo/shell/utils.js:883:9

shellHelper@src/mongo/shell/utils.js:790:15

@(shellhelp2):1:1 --->報錯沒有權限

2、用戶和密碼登錄用戶

> db.auth("cg","lianshi");

1

使用db.auth(cg,lianshi)啓用auth認證,看到返回的值爲1,這就表示啓動成功了,然後我們再使用命令查看用戶和數據庫

> show dbs

mytest  0.000GB

>  db.student.insert({"id":"2","name":"yxy"})

WriteResult({ "nInserted" : 1 })

其他用戶命令:

1、創建普通用戶(創建用戶cg,對mytest數據庫讀寫權限)

> db.createUser({user:"cg",pwd:"lianshi",roles:[{role:"readWrite",db:"mytest"}]})

2、刪除用戶>db.dropUser("yonghu")

3、修改用戶密碼

db.updateUser("cg",{pwd:"123456"})

4、進入數據mytest,用戶名密碼認證

> db.auth("cg","lianshi");

1

5、客戶端工具授權登錄連接mongo數據庫

用戶名和密碼連接數據庫

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章