MongoDB 3.0 使用者建立

jyzhou發表於2015-06-30

摘要:

      MongoDB 3.0 安全許可權訪問控制,在新增使用者上面3.0版本和之前的版本有很大的區別,這裡就說明下3.0的新增使用者的方法。

環境、測試:

      安裝MongoDB之後,先關閉auth認證,進入檢視資料庫,只有一個local庫,admin庫是不存在的:

root@zhoujinyi:/usr/local/mongo4# mongo --port=27020
MongoDB shell version: 3.0.4
connecting to: 127.0.0.1:27020/test
2015-06-29T09:31:08.673-0400 I CONTROL  [initandlisten] 
> show dbs;
local  0.078GB

現在需要建立一個帳號,該賬號需要有grant許可權,即:賬號管理的授權許可權。注意一點,帳號是跟著庫走的,所以在指定庫裡授權,必須也在指定庫裡驗證(auth)。

> use admin
switched to db admin
> db.createUser(
...   {
...     user: "dba",
...     pwd: "dba",
...     roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
...   }
... )
Successfully added user: {
    "user" : "dba",
    "roles" : [
        {
            "role" : "userAdminAnyDatabase",
            "db" : "admin"
        }
    ]
}

上面加粗的就是執行的命令:

user:使用者名稱

pwd:密碼

roles:指定使用者的角色,可以用一個空陣列給新使用者設定空角色;在roles欄位,可以指定內建角色和使用者定義的角色。role裡的角色可以選:

  Built-In Roles(內建角色):
    1. 資料庫使用者角色:read、readWrite;
    2. 資料庫管理角色:dbAdmin、dbOwner、userAdmin;
    3. 叢集管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager;
    4. 備份恢復角色:backuprestore5. 所有資料庫角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase
    6. 超級使用者角色:root  
    // 這裡還有幾個角色間接或直接提供了系統超級使用者的訪問(dbOwner 、userAdmin、userAdminAnyDatabase)
    7. 內部角色:__system

具體角色: 

Read:允許使用者讀取指定資料庫
readWrite:允許使用者讀寫指定資料庫
dbAdmin:允許使用者在指定資料庫中執行管理函式,如索引建立、刪除,檢視統計或訪問system.profile
userAdmin:允許使用者向system.users集合寫入,可以找指定資料庫裡建立、刪除和管理使用者
clusterAdmin:只在admin資料庫中可用,賦予使用者所有分片和複製集相關函式的管理許可權。
readAnyDatabase:只在admin資料庫中可用,賦予使用者所有資料庫的讀許可權
readWriteAnyDatabase:只在admin資料庫中可用,賦予使用者所有資料庫的讀寫許可權
userAdminAnyDatabase:只在admin資料庫中可用,賦予使用者所有資料庫的userAdmin許可權
dbAdminAnyDatabase:只在admin資料庫中可用,賦予使用者所有資料庫的dbAdmin許可權。
root:只在admin資料庫中可用。超級賬號,超級許可權

剛建立了 userAdminAnyDatabase 角色,用來管理使用者,可以通過這個角色來建立、刪除使用者。驗證:需要開啟auth引數。

root@zhoujinyi:/usr/local/mongo4# mongo --port=27020
MongoDB shell version: 3.0.4
connecting to: 127.0.0.1:27020/test
> show dbs;    ####沒有驗證,導致沒許可權。
2015-06-29T10:02:16.634-0400 E QUERY    Error: listDatabases failed:{
    "ok" : 0,
    "errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",
    "code" : 13
}
    at Error (<anonymous>)
    at Mongo.getDBs (src/mongo/shell/mongo.js:47:15)
    at shellHelper.show (src/mongo/shell/utils.js:630:33)
    at shellHelper (src/mongo/shell/utils.js:524:36)
    at (shellhelp2):1:1 at src/mongo/shell/mongo.js:47
> use admin        #驗證,因為在admin下面新增的帳號,所以要到admin下面驗證。
switched to db admin
> db.auth('dba','dba')
1
> show dbs;
admin  0.078GB
local  0.078GB
> use test        #在test庫裡建立帳號
switched to db test
> db.createUser(
...     {
...       user: "zjyr",
...       pwd: "zjyr",
...       roles: [
...          { role: "read", db: "test" }    #只讀帳號
...       ]
...     }
... )
Successfully added user: {
    "user" : "zjyr",
    "roles" : [
        {
            "role" : "read",
            "db" : "test"
        }
    ]
}
> db.createUser(
...     {
...       user: "zjy",
...       pwd: "zjy",
...       roles: [
...          { role: "readWrite", db: "test" }   #讀寫帳號
...       ]
...     }
... )
Successfully added user: {
    "user" : "zjy",
    "roles" : [
        {
            "role" : "readWrite",                #讀寫賬號
            "db" : "test"
        }
    ]
}
> show users;                                    #檢視當前庫下的使用者
{
    "_id" : "test.zjyr",
    "user" : "zjyr",
    "db" : "test",
    "roles" : [
        {
            "role" : "read",
            "db" : "test"
        }
    ]
}
{
    "_id" : "test.zjy",
    "user" : "zjy",
    "db" : "test",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "test"
        }
    ]
}

上面建立了2個帳號,現在驗證下:驗證前提需要一個集合

> db.abc.insert({"a":1,"b":2})              #插入失敗,沒有許可權,userAdminAnyDatabase 許可權只是針對使用者管理的,對其他是沒有許可權的。
WriteResult({
    "writeError" : {
        "code" : 13,
        "errmsg" : "not authorized on test to execute command { insert: \"abc\", documents: [ { _id: ObjectId('55915185d629831d887ce2cb'), a: 1.0, b: 2.0 } ], ordered: true }"
    }
})
> 
bye
root@zhoujinyi:/usr/local/mongo4# mongo --port=27020
MongoDB shell version: 3.0.4
connecting to: 127.0.0.1:27020/test
> use test
switched to db test
> db.auth('zjy','zjy')       #用建立的readWrite帳號進行寫入
1
> db.abc.insert({"a":1,"b":2})
WriteResult({ "nInserted" : 1 })
> db.abc.insert({"a":11,"b":22})
WriteResult({ "nInserted" : 1 })
> db.abc.insert({"a":111,"b":222})
WriteResult({ "nInserted" : 1 })
> db.abc.find()
{ "_id" : ObjectId("559151a1b78649ebd8316853"), "a" : 1, "b" : 2 }
{ "_id" : ObjectId("559151cab78649ebd8316854"), "a" : 11, "b" : 22 }
{ "_id" : ObjectId("559151ceb78649ebd8316855"), "a" : 111, "b" : 222 }
> db.auth('zjyr','zjyr')       #切換到只有read許可權的帳號
1
> db.abc.insert({"a":1111,"b":2222})  #不能寫入
WriteResult({
    "writeError" : {
        "code" : 13,
        "errmsg" : "not authorized on test to execute command { insert: \"abc\", documents: [ { _id: ObjectId('559151ebb78649ebd8316856'), a: 1111.0, b: 2222.0 } ], ordered: true }"
    }
})
> db.abc.find()        #可以檢視
{ "_id" : ObjectId("559151a1b78649ebd8316853"), "a" : 1, "b" : 2 }
{ "_id" : ObjectId("559151cab78649ebd8316854"), "a" : 11, "b" : 22 }
{ "_id" : ObjectId("559151ceb78649ebd8316855"), "a" : 111, "b" : 222 }

有沒有一個超級許可權?不僅可以授權,而且也可以對集合進行任意操作?答案是肯定的,只是不建議使用。那就是role角色設定成root

> db.auth('dba','dba')
1
> db.createUser(
...  {
...    user: "zhoujinyi",
...    pwd: "zhoujinyi",
...    roles: [
...       { role: "root", db: "admin" }      #超級root帳號
...    ]
...  }
... )
Successfully added user: {
    "user" : "zhoujinyi",
    "roles" : [
        {
            "role" : "root",
            "db" : "admin"
        }
    ]
}
> 
> show users;              #檢視當前庫下的使用者
{
    "_id" : "admin.dba",
    "user" : "dba",
    "db" : "admin",
    "roles" : [
        {
            "role" : "userAdminAnyDatabase",
            "db" : "admin"
        }
    ]
}
{
    "_id" : "admin.zhoujinyi",
    "user" : "zhoujinyi",
    "db" : "admin",
    "roles" : [
        {
            "role" : "root",
            "db" : "admin"
        }
    ]
}
> use admin
switched to db admin
> db.auth('zhoujinyi','zhoujinyi')
1
> use test
switched to db test
> db.abc.insert({"a":1,"b":2})
WriteResult({ "nInserted" : 1 })
> db.abc.insert({"a":1111,"b":2222})          #許可權都有
WriteResult({ "nInserted" : 1 })
> db.abc.find()
{ "_id" : ObjectId("5591539bb78649ebd8316857"), "a" : 1, "b" : 2 }
{ "_id" : ObjectId("559153a0b78649ebd8316858"), "a" : 1111, "b" : 2222 }
> db.abc.remove({})
WriteResult({ "nRemoved" : 2 })

因為帳號都是在當前需要授權的資料庫下授權的,那要是不在當前資料庫下會怎麼樣?

> db
admin
> db.createUser(
...  {
...    user: "dxy",
...    pwd: "dxy",
...    roles: [
...       { role: "readWrite", db: "test" },     #在當前庫下建立其他庫的帳號,在admin庫下建立test、abc庫的帳號
...       { role: "readWrite", db: "abc" }         
...    ]
...  }
... )
Successfully added user: {
    "user" : "dxy",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "test"
        },
        {
            "role" : "readWrite",
            "db" : "abc"
        }
    ]
}
> 
> show users;
{
    "_id" : "admin.dba",
    "user" : "dba",
    "db" : "admin",
    "roles" : [
        {
            "role" : "userAdminAnyDatabase",
            "db" : "admin"
        }
    ]
}
{
    "_id" : "admin.zhoujinyi",
    "user" : "zhoujinyi",
    "db" : "admin",
    "roles" : [
        {
            "role" : "root",
            "db" : "admin"
        }
    ]
}
{
    "_id" : "admin.dxy",
    "user" : "dxy",
    "db" : "admin",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "test"
        },
        {
            "role" : "readWrite",
            "db" : "abc"
        }
    ]
}
> use test
switched to db test
> db.auth('dxy','dxy')          #在admin下建立的帳號,不能直接在其他庫驗證,
Error: 18 Authentication failed.
0
> use admin
switched to db admin            #只能在帳號建立庫下認證,再去其他庫進行操作。
> db.auth('dxy','dxy')
1
> use test
switched to db test
> db.abc.insert({"a":1111,"b":2222})
WriteResult({ "nInserted" : 1 })
> use abc
switched to db abc
> db.abc.insert({"a":1111,"b":2222})
WriteResult({ "nInserted" : 1 })

上面更加進一步說明資料庫帳號是跟著資料庫來走的,哪裡建立哪裡認證。

建立了這麼多帳號,怎麼檢視所有帳號

>  use admin
switched to db admin
> db.auth('dba','dba')
1
> db.system.users.find().pretty()
{
    "_id" : "admin.dba",
    "user" : "dba",
    "db" : "admin",
    "credentials" : {
        "SCRAM-SHA-1" : {
            "iterationCount" : 10000,
            "salt" : "KfDUzCOIUo7WVjFr64ZOcQ==",
            "storedKey" : "t4sPsKG2dXnZztVYj5EgdUzT9sc=",
            "serverKey" : "2vCGiq9NIc1zKqeEL6VvO4rP26A="
        }
    },
    "roles" : [
        {
            "role" : "userAdminAnyDatabase",
            "db" : "admin"
        }
    ]
}
{
    "_id" : "test.zjyr",
    "user" : "zjyr",
    "db" : "test",
    "credentials" : {
        "SCRAM-SHA-1" : {
            "iterationCount" : 10000,
            "salt" : "h1gOW3J7wzJuTqgmmQgJKQ==",
            "storedKey" : "7lkoANdxM2py0qiDBzFaZYPp1cM=",
            "serverKey" : "Qyu6IRNyaKLUvqJ2CAa/tQYY36c="
        }
    },
    "roles" : [
        {
            "role" : "read",
            "db" : "test"
        }
    ]
}
{
    "_id" : "test.zjy",
    "user" : "zjy",
    "db" : "test",
    "credentials" : {
        "SCRAM-SHA-1" : {
            "iterationCount" : 10000,
            "salt" : "afwaKuTYPWwbDBduQ4Hm7g==",
            "storedKey" : "ebb2LYLn4hiOVlZqgrAKBdStfn8=",
            "serverKey" : "LG2qWwuuV+FNMmr9lWs+Rb3DIhQ="
        }
    },
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "test"
        }
    ]
}
{
    "_id" : "admin.zhoujinyi",
    "user" : "zhoujinyi",
    "db" : "admin",
    "credentials" : {
        "SCRAM-SHA-1" : {
            "iterationCount" : 10000,
            "salt" : "pE2cSOYtBOYevk8tqrwbSQ==",
            "storedKey" : "TwMxdnlB5Eiaqg4tNh9ByNuUp9A=",
            "serverKey" : "Mofr9ohVlFfR6/md4LMRkOhXouc="
        }
    },
    "roles" : [
        {
            "role" : "root",
            "db" : "admin"
        }
    ]
}
{
    "_id" : "admin.dxy",
    "user" : "dxy",
    "db" : "admin",
    "credentials" : {
        "SCRAM-SHA-1" : {
            "iterationCount" : 10000,
            "salt" : "XD6smcWX4tdg/ZJPoLxxRg==",
            "storedKey" : "F4uiayykHDp/r9krAKZjdr+gqjM=",
            "serverKey" : "Kf51IU9J3RIrB8CFn5Z5hEKMSkw="
        }
    },
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "test"
        },
        {
            "role" : "readWrite",
            "db" : "abc"
        }
    ]
}
> db.system.users.find().count()
5

備份還原使用那個角色的帳號?之前建立的帳號zjy:test庫讀寫許可權;zjyr:test庫讀許可權

root@zhoujinyi:~# mongodump --port=27020 -uzjyr -pzjyr --db=test -o backup   #只要讀許可權就可以備份
2015-06-29T11:20:04.864-0400    writing test.abc to backup/test/abc.bson
2015-06-29T11:20:04.865-0400    writing test.abc metadata to backup/test/abc.metadata.json
2015-06-29T11:20:04.866-0400    done dumping test.abc
2015-06-29T11:20:04.867-0400    writing test.system.indexes to backup/test/system.indexes.bson


root@zhoujinyi:~# mongorestore --port=27020 -uzjy -pzjy --db=test backup/test/  #讀寫許可權可以進行還原
2015-06-29T11:20:26.607-0400    building a list of collections to restore from backup/test/ dir
2015-06-29T11:20:26.609-0400    reading metadata file from backup/test/abc.metadata.json
2015-06-29T11:20:26.609-0400    restoring test.abc from file backup/test/abc.bson
2015-06-29T11:20:26.611-0400    error: E11000 duplicate key error index: test.abc.$_id_ dup key: { : ObjectId('559154efb78649ebd831685a') }
2015-06-29T11:20:26.611-0400    restoring indexes for collection test.abc from metadata
2015-06-29T11:20:26.612-0400    finished restoring test.abc
2015-06-29T11:20:26.612-0400    done

 

相關連線:

MongoDB 許可權控制系統簡介

相關文章