Infinite | Squares

Art of code and more

Add User to MongoDB

MongoDB is easy enough to use that you don’t even have to think about adding user when start using it. This could lead to a problem down the road when you are need to open your database access to public internet. And also the provided free version do not support SSL!. But that is another issue.

For now, lets take note on how we can start adding user (and password) to protect our database access.

Add admin

First you want to start add admin user which can manage other users

1
$ mongo

then in Mongo shell

1
> use admin
1
2
3
4
5
6
7
8
9
10
11
12
13
> db.createUser(
  {
    user: "admin",
    pwd: "adminpass",
    roles:
    [
      {
        role: "userAdminAnyDatabase",
        db: "admin"
      }
    ]
  }
)

Then exit shell by Ctrl+C or type exit

Enable auth on MongoD

edit the mongo conf file with

1
$ sudo nano /etc/mongod.conf

Uncomment this line

1
auth=true

If you want to access from other machine change the line

1
bind_ip=127.0.0.1

to

1
bind_ip=0.0.0.0

More protection is necessary in production servers. I will explore this later.

Then restart mongod

1
$ sudo service mongod restart

Add user to the database

Open Mongo shell

1
$ mongo
1
2
> use admin
> db.auth("admin","pwd:"adminpass")

Add new database and its user

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
> use newdb
> db.createUser(
  {
    user: "user",
    pwd: "pass",
    roles:
    [
      {
        role: "dbOwner",
        db: "newdb"
      }
    ]
  }
)
> db.auth("user","pass")
> show collections

There you have it. Now your MongoDB is user-password protected. Its a small step but necessary.

Comments