How to add and update user accounts in MongoDB database

In this post I will discuss one of the most important topics related to any kind of applications, security. If you are using MongoDB database then it is important that you know about some basic security related details. In previous posts I discussed the basic steps of installing MongoDB and configuring to run it as windows service. As I explained previously, every aspect of MongoDB run time has to be configured. Same is true for configuring security as well. When MongoDB is installed you are able to perform all operations and you did not have to log in or anything like that. In production environment you do not want to have open access to your database. This means MongoDB has to be told that all operations should be authenticated. Before going any further, let me point out that MongoDB has very detailed information on security in following section in documentation.

MongoDB Security

auth Setting

There is auth setting that you have to specify when configuring running of database. The default value of this setting is false. This means that all of your operations, queries etc. in MongoDB can be performed by anyone who has access to your server and can launch mongo shell. There is a reason that default value is false. If by default authentication is turned on, you will not be able to perform any operations out of the box. To make MongoDB authenticate all requests, set the value of auth setting to true. In configuration file, the entry will look like below.

##enable authentication
auth=true
    

Set up an administrator account before turning on authenticationM

This is for the same reason that auth settings is set to false by default. If you turn on authentication before setting up administration account, then you will be locked out of MongoDB. So let's see how to set up administrator account. First you will need to set up a super user account that can control security on all databases in your installation. In MongoDB, you have to explicitly authorize each type of action by adding required roles to an account. In MongoDB there is inbuilt admin database. This database contains secured documents (aka records) that store information about user accounts. In this database there is system.users collection that contain document about each user account. You will be adding a new user record in this collection. There are three basic properties of user account that you will specify to create an account. There properties are:

  • user: This property contains login name for the account
  • pwd: This property is used to specify password for the account
  • roles: This property is an array of roles assigned to the user account

Important property of this process is what roles should be assigned to the user. MongoDB has list of all roles in documentation here. For now we will focus on roles specified under section Any Database Roles. In this section you will find role called userAdminAnyDatabase. As the name suggests a user with role can be used for administration of user accounts in any database. One thing that needs to be emphasized here is that this role only provides privileges to manipulate user accounts only. This role does not provide you access to executing any other database operations. I will show you in a little bit what will happen if you try to execute any task other than user administration with this account. Let's go ahead and create our super user account for user management in our database.

Steps to create user account in MongoDB
  • Launch mongo shell by executing mongo.exe command on command line. If your MongoDB database is listening on any port other than default 27017, you will get an error. In that case you will need to specify port number with this command as well. For example in my case, I have to execute following command.

    mongo --port 29001
  • Switch to use admin database. This is similar to executing use {dbname} statement in MS SQL database.

    > use admin
    switched to db admin
    
  • Now use addUser method to add user account/

    >db.addUser( { user: "mysuperadmin",
                  pwd: "mysuperadminpassword",
                  roles: [ "userAdminAnyDatabase" ]
                } )
    

    Now execute show users command to check if you have your user account created or not.

    > show users
    {
            "_id" : ObjectId("52befaddeb8cb0bc81816675"),
            "user" : "mysuperadmin",
            "pwd" : "ab57d35ad7dc76533c53f30b3028ba79",
            "roles" : [
                    "userAdminAnyDatabase"
            ]
    }
    

Now that we have our super admin user management account created, modify your database configuration file to set value of auth setting to true. Restart windows service so that new configuration can take into affect. If you execute show users command in mongo shell, you will get an error as shown below.

> show users
Sat Dec 28 11:56:59.058 error: { "$err" : "not authorized for query on test.system.users", 
    "code" : 16550 } at src/mongo/shell/query.js:128

Error is very clearly telling us that now unauthorized access to database is not allowed. This means to perform any action we will have to login. You will use db.auth function to login into MongoDB.

> use admin
switched to db admin
> db.auth("mysuperadmin","mysuperadminpassword")
1
> show users
{
        "_id" : ObjectId("52befaddeb8cb0bc81816675"),
        "user" : "mysuperadmin",
        "pwd" : "ab57d35ad7dc76533c53f30b3028ba79",
        "roles" : [
                "userAdminAnyDatabase"
        ]
}

Now we are good to go and start managing users on other databases in MongoDB. Before we go further, let's see what will happen if we try to execute any command with user that only has userAdminAnyDatabase role.

> show databases
Sat Dec 28 12:00:06.155 listDatabases failed:{ "ok" : 0, "errmsg" : "unauthorized" } 
  at src/mongo/shell/mongo.js:46

As you can see that we authorization error. As I mentioned earlier userAdminAnyDatabase role only provides user management capabilities. It does not grant you any other rights on any database.

How to create a user account in Mongo database

Now we have super admin account created, we continue to add user accounts to individual databases. The same security prinicpals applies to user accounts for individual databases i.e. you have to explicitly specify what roles should be added to a user account to perform the job that account is supposed to perform. Let's first add an account that can read and write data to a database. You will follow the same steps that you used for adding super user account except that we will switch to database in which user account is to be added. As an example I executed following command on my "Commerce" database.

> use Commerce
switched to db Commerce
>db.addUser( { user: "commerceadmin", pwd: "mypassword", roles: [ "readWrite" ]} )
> db.system.users.findOne()
{
        "_id" : ObjectId("52befe4deb8cb0bc81816676"),
        "user" : "commerceadmin",
        "pwd" : "6a87acc2898b36a0ed9b0f487ed0b065",
        "roles" : [
                "readWrite"
        ]
}

Now I have a user account that I will use to authorize all read and write operations in my database named Commerce. But there is small issue. We have an account that perform CRUD operations but how are we going to do user management for this database. You have choice of either using the super user account to manage users for individual databases or we can create a new account with userAdmin role or elevate one of the existing accounts and add userAdmin role to it. For now I am going to add userAdmin role to commerceadmin account that I just created.

How to add a role to MongoDB database

User account is nothing but a document (record) in system.users collection. So updating a user's role is nothing different than updating the record and add a new role value to roles collection. I executed following commands to add userAdmin role to the account.

> db.system.users.update({user:"commerceadmin"},{$push:{roles:"userAdmin"}})
> db.system.users.findOne()
{
        "_id" : ObjectId("52befe4deb8cb0bc81816676"),
        "pwd" : "6a87acc2898b36a0ed9b0f487ed0b065",
        "roles" : [
                "readWrite",
                "userAdmin"
        ],
        "user" : "commerceadmin"
}

You need to pay attention to what roles you add to an account and what that role is capable of doing it. I have added userAdmin role to the account. This role is used for user management only. Therefore if you want to add a user to your database who is going to be responsible for user management only and not allowed to perform any other action on any collections, then add a new account that has only one role, userAdmin.

Now we are all set with using authentication and authorization mechanism for our MongoDB installation. In next post I will show how to use C# code to authenticate a CRUD operation on your database.

comments powered by Disqus

Blog Tags