简体   繁体   中英

Create mongo user with right to read local database

I would like to create a mongo user who can read local database. I try to use command on local database:

db.createUser(
  {     user: "readonlyuser", pwd: "loh8Ephi",
    roles: [ { role: "read", db: "local" } ]
})

But - it doesn't work. I receive:

connecting to: local
2015-12-21T14:08:07.904+0100 Error: couldn't add user: Cannot create users in the local database at src/mongo/shell/db.js:1054

I've tried to create that user against admin database:

> use admin
switched to db admin
> db.createUser(
...   {     user: "readonlyuser", pwd: "loh8Ephi", roles: [ { role: "read", db: "local" } ] })

Successfully added user: {
"user" : "readonlyuser",
"roles" : [
    {
        "role" : "read",
        "db" : "local"
    }
]

And now i try to connect:

undefine@machine:~$ mongo -u readonlyuser -p loh8Ephi local
MongoDB shell version: 2.6.11
connecting to: local
2015-12-21T15:35:19.190+0100 Error: 18 { ok: 0.0, errmsg: "auth failed", code: 18 } at src/mongo/shell/db.js:1292
exception: login failed

How to create readonly user who have access only to local database?

According the documentation , you cannot create users on the local database. Instead you can run your createUser query against the admin database:

use admin
db.createUser(
 {     user: "readonlyuser", pwd: "loh8Ephi",
   roles: [ { role: "read", db: "local" } ]
})

Please note that you will have to authenticate against the admin database when connecting.

I would do it like below

use admin
db.getSiblingDB("local").runCommand( { "createUser" : "mongoread", "pwd": "read0nly", "customData" : { "description": "mongo readonly user" }, "roles" : [ {"role" : "read","db" : "local"}] },{ w: "majority" , wtimeout: 5000 } );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM