創建管理員賬戶:
1.登錄
[root@MongoDB ~]# mongo
2.切換到admin數據庫創建賬戶
> use admin switched to db admin
3.用戶創建用戶方法
db.createUser()
role用於指定哪個用戶,db指定哪個數據庫
> db.createUser({user:"admin",pwd:"123456",roles:[{ role:"root", db:"admin" } ] }) Successfully added user: { "user" : "admin", "roles" : [ { "role" : "root", "db" : "admin" } ] }
4.退出MongoDB命名行
> quit() [root@MongoDB ~]#
或者使用exit 退出MongoDB
5.啟用權限管理
修改MongoDB安裝目錄中的配置文件 /etc/mongod.conf
[root@MongoDB ~]# vim /etc/mongod.conf
將#security:的注釋去掉,然后添加authorization: enabled #注意authorization前面要有兩個空格
security:
authorization: enabled
重啟MongoDB
[root@MongoDB ~]# systemctl restart mongod
使用創建的用戶登錄MongoDB
[root@MongoDB ~]# mongo --host 127.0.0.1 --port 27017 -u "admin" -p "123456" --authenticationDatabase "admin"
--host 指定登錄的主機,
--port 指定登錄端口
-u 指定登錄用戶
-p 指定用戶登錄密碼
-- authenticationDatabase 指定認證的數據庫
如何使用/查看/刪除用戶:
use admin
用於列出MongoDB 關聯這個數據庫的所有的用戶,需要先切換到指定數據庫 例如:需要先切換到admin數據庫
db.system.users.find()
> db.system.users.find() { "_id" : "admin.admin", "user" : "admin", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "1pm1kS2JTR/iLon8pY1Vkg==", "storedKey" : "k16n9/CH3K/spAIl9yNcl7xtw4k=", "serverKey" : "3zbHiGF13FicptAnNYQOMin9Jso=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "3SXNHNIPsGAdzCE5rkw9O+RIgGa8Ui8T41g3cA==", "storedKey" : "jF2hv4p9LWqGba95+5zfLLPC62jL7irlF66XOFvCbUo=", "serverKey" : "2gWAdyuBJOdN6v2EfLwiADAarZOJ0R3xHX5ttn0zOkE=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
用於列出當前庫下的所有用戶
show users
> show users { "_id" : "admin.admin", "user" : "admin", "db" : "admin", "roles" : [ { "role" : "root", "db" : "admin" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] }
用戶刪除當前庫下的指定的用戶
db.dropUser()
> db.dropUser('admin') true
返回true 刪除成功