User and roles

Apart from some authentication systems, MongoDB has users and roles which can be applied to different databases. First, let’s see how to create an admin user for admin database with god-like (root) permissions.

Root permissions for all mongo databases:

use admin
db.createUser(
{
user: “admin”,
pwd: “KeepASecret”,
roles: [ “root” ]

}
)
Successfully added user: { “user” : “admin”, “roles” : [ “root” ] }

Now mongodb will not show you anything. Logout and log in again, this time using those credentials.

root@usurbil:# mongo -u admin -p KeepASecret admin
MongoDB shell version: 2.6.1
connecting to: admin
>

To check the permissions for a certain user:

db.runCommand(
{
usersInfo:”admin”,
showPrivileges:true
}
)

One user just for one database

Somo basic permissions for just one db:

use myotherdb
db.createUser(
{
user: “myotherdbuser”,
pwd: “KeepASecret”,
roles: [“readWrite”,”dbAdmin”]
}
)

That’s it, first we access admin database and then we run db.createUser command with obvious options in json syntax. If anything fails we can just stop mongod and re-run it without the –auth flag. If you try to access with your mongoshell using this admin user you’ll get:

root@linux:# mongo  -u admin -p wrongpass admin
MongoDB shell version: 2.6.1
connecting to: admin
2014-07-18T01:32:04.702+0200 Error: 18 { ok: 0.0, errmsg: “auth failed”, code: 18 } at src/mongo/shell/db.js:1210
exception: login failed
root@linux:#

We could also log without any user and authenticate from the mongo shell

root@linux:# mongo –host localhost admin
MongoDB shell version: 2.6.1
connecting to: localhost:27017/admin
> db.auth({user: ‘admin’,pwd:’KeepASecret’})

Changing password

To change the password, enter as admin, change to the database of that user and execute changeUserPassword command

use myotherdb
switched to db myotherdb
> db.changeUserPassword(“myotherdbuser”, “1234567”)

Updating permissions

Database access are stored in collections of course, in db.system.users. So we can just execute update queries to add new roles, which is but an array where we can push or pop values.

db.system.users.update({_id:”admin.admin”},{$push:{“roles”:{“role”:”root”,”db”:”mytotherdb”}}})

Users in MongoDB

Leave a Reply