天天看點

mongodb使用者權限配置

第一次安裝monogdb時,admin資料庫中沒有任何使用者,此時不管是否以--auth方式啟動資料庫,其他資料庫(比如test資料庫)中的使用者都可以對另外的資料庫(比如db1資料庫)中的資料進行操作~!

> show dbs

local   (empty)

#檢視admin 資料庫中的使用者資訊,因為是剛建立的資料庫是以user 為空~!

> use admin

switched to db admin

通過db.createUser()建立:

db.createUser(

  {

        user:"peiwouser",

        pwd:"peiwo2015",

       roles:

        [ 

           {

            role:"dbOwner",

            db:"peiwo"

            }

        ]

    }

);

> mongo  

> use admin  

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

1  

定義:

建立一個資料庫新使用者用db.createUser()方法,如果使用者存在則傳回一個使用者重複錯誤。

文法:

db.createUser(user, writeConcern)

    user這個文檔建立關于使用者的身份認證和通路資訊;

    writeConcern這個文檔描述保證MongoDB提供寫操作的成功報告。

· user文檔,定義了使用者的以下形式:

{ user: "<name>",

  pwd: "<cleartext password>",

  customData: { <any information> },

  roles: [

    { role: "<role>", db: "<database>" } | "<role>",

    ...

  ]

}

user文檔字段介紹:

    user字段,為新使用者的名字;

    pwd字段,使用者的密碼;

    cusomData字段,為任意内容,例如可以為使用者全名介紹;

    roles字段,指定使用者的角色,可以用一個空數組給新使用者設定空角色;

    在roles字段,可以指定内置角色和使用者定義的角色。

    Built-In Roles(内置角色):

    1. 資料庫使用者角色:read、readWrite;

    2. 資料庫管理角色:dbAdmin、dbOwner、userAdmin;

    3. 叢集管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager;

    4. 備份恢複角色:backup、restore;

    5. 所有資料庫角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase

    6. 超級使用者角色:root  

    // 這裡還有幾個角色間接或直接提供了系統超級使用者的通路(dbOwner 、userAdmin、userAdminAnyDatabase)

    7. 内部角色:__system

    PS:關于每個角色所擁有的操作權限可以點選上面的内置角色連結檢視詳情。

· writeConcern文檔(官方說明)

    w選項:允許的值分别是 1、0、大于1的值、"majority"、<tag set>;

    j選項:確定mongod執行個體寫資料到磁盤上的journal(日志),這可以確定mongd以外關閉不會丢失資料。設定true啟用。

    wtimeout:指定一個時間限制,以毫秒為機關。wtimeout隻适用于w值大于1。

例如:在products資料庫建立使用者accountAdmin01,并給該使用者admin資料庫上clusterAdmin和readAnyDatabase的角色,products資料庫上readWrite角色。

use products

db.createUser( { "user" : "accountAdmin01",

                 "pwd": "cleartext password",

                 "customData" : { employeeId: 12345 },

                 "roles" : [ { role: "clusterAdmin", db: "admin" },

                             { role: "readAnyDatabase", db: "admin" },

                             "readWrite"

                             ] },

               { w: "majority" , wtimeout: 5000 } )

驗證:

mongo -u accountAdmin01 -p yourpassward --authenticationDatabase products

linux 遠端連接配接

/usr/local/mongodb/bin/mongo 127.0.0.1/peiwo -u peiwouser -p

     本文轉自aaron428 51CTO部落格,原文連結:http://blog.51cto.com/aaronsa/1741515,如需轉載請自行聯系原作者