MongoDB login

Executive Summary: This is how to fix a MongoDB installation on a server so that it is password protected.

If you do a vanilla install of MongoDB on your server, you may end up with a mongo.conf that looks the same as the one here: https://github.com/mongodb/mongo/blob/master/rpm/mongod.conf. If you notice, this *.conf has nothing in the security section.

These are the steps to follow:

  1. Make an admin user.
  2. Change the mongod.conf to use security.
  3. Login as the admin user and create other users

Use user/password from CLI

JavaScript connection string with user/password

Appendix A - References

Make an admin user.

Before you fix the mongod.conf to use authentication, make yourself an admin user. Pick a user name and password:

{adminuser} {adminpassword}

From the mongo cli:

use admin;
var user = {
... "user": "{adminuser}",
... "pwd":"{adminpassword}",
... roles: [
... {
... "role": "userAdminAnyDatabase",
... "db": "admin"
... }
... ]
... }


db.createUser(user);

Change the mongod.conf to use security.

On CentOS, the mongod.conf was located at /etc/mongod.conf.

So, I changed from this:

#security:

to this:

security:
  authorization: enabled

After you change mongod.conf, you have to restart mongod for it to take effect. For CentOS, from the command line:

sudo service mongod restart

Login as the admin user and create other users

Next, you will want to make a user to login to a specific database. I logged in as the admin user from the mongo CLI:

mongo -u "{adminuser}" -p "{adminpassword}" --authenticationDatabase "admin"

To make a login for the {database}, pick a username and password:

{username} {password}

Make a user:

use zakhelp;
db.createUser(
    {
    user: "{username}",
    pwd: "{password}",
    roles: [
    {
    role: "readWrite", db: "{database}"
    }
    ]
    }
)

Use user/password from CLI

You can login in from the command line using that user like this:

mongo -u "{username}" -p "{password}" --authenticationDatabase "{database}"

JavaScript connection string with user/password

To use the username and database in a connection string inside JavaScript:

var usedDb = 'mongodb://{username}:{password}@localhost/zakhelp';

mongoose.connect(usedDb);

Appendix A - References

These were the most useful references:

Description URL
This was an enlightening article about a gigantic security hole in a previous version on MongoDB 2.6 tothenew
This is a perfectly confusing article on all the security options you can set in mongod.conf docs.mongodb
This is a reasonably 'follow-able' article on how to do what I did in this paper. What I really needed from this article was the following link that helped me figure out what to put in mongo.conf docs.mongodb.tutorial.enable-authentication
This is a friendly article that covers the same information as the confusing tutorial from Mongo. tgrall

results matching ""

    No results matching ""