Background

在MongoDB中要創建User其實蠻複雜的. 你必須先到admin這個資料庫設定用戶,系統才會視為你要啟用「帳戶功能」.

1. Add root user

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

2. Exit and Test

成功加入root之後要重新啟用MongoDB.

# stop mongod first kill the process or sudo service mongod stop
# start mongod 
$ sudo mongod -f /etc/mongod.conf --auth --fork # remember to add --auth option.
$ mongo

然後在沒有驗證的情況下登入, 你會發現幾乎所有的指令都不能操作. 會顯示跟下面差不多的訊息.

taiker@mongodb:~$ mongo
MongoDB shell version v3.4.0
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.0
> show tables
2016-12-03T12:23:41.011+0000 E QUERY    [main] Error: listCollections failed: {
        "ok" : 0,
        "errmsg" : "not authorized on test to execute command { listCollections: 1.0, filter: {} }",
        "code" : 13,
        "codeName" : "Unauthorized"
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype._getCollectionInfosCommand@src/mongo/shell/db.js:805:1
DB.prototype.getCollectionInfos@src/mongo/shell/db.js:817:19
DB.prototype.getCollectionNames@src/mongo/shell/db.js:828:16
shellHelper.show@src/mongo/shell/utils.js:748:9
shellHelper@src/mongo/shell/utils.js:645:15
@(shellhelp2):1:1

所以在登入時必須填上登入資訊.

$ mongo -u "root" -p "password" --authenticationDatabase "admin"

2. Add other roles

那我們還是不希望使用Root權限來操作一切. 所以必須還要新增其他role來管理DB. 那官方文件上有許多Roles的定義. 大家可以參考&自己決定要新增什麼role. 在這邊我用readWriteAnyDatabase來表示.

> use admin
> db.createUser(
{
    user: "userReadWrite",
    pwd: "passwordReadWrite",
    roles: [ "readWriteAnyDatabase" ]
}
)

創好之後再使用新創的user登入

$ mongo -u "userReadWrite" -p "passwordReadWrite" --authenticationDatabase "admin"

就會發現下列warning的資訊不見了. 然後就可以根據你給予的權限操作DB. 這樣就差不多告一個段落了.

Server has startup warnings: 
2016-12-03T12:23:35.508+0000 I STORAGE  [initandlisten] 
2016-12-03T12:23:35.775+0000 I CONTROL  [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
2016-12-03T12:23:35.775+0000 I CONTROL  [initandlisten]

Reference