Out of the box, MongoDB does not activate authentication when you connect your application to it. You need to set it up.
So on development your application’s connection string can look like this,
mongodb://localhost/myAppDB
This is convenient on development but totally not secure when deploying your system on “Production”. So I wrote this article as a reference to my future self and others. With this, I’m running Ubuntu 14.0X and MongoDB 3.X and the application I’m connecting is built on top of MEAN.JS. In my case, MongoDB is already installed and currently running as a service.
Start a terminal and open mongo shell using this command:
mongo
The command will connect you to your unsecured MongoDB instance.
Create a root admin user thru this script. Change the user
and pwd
values to your liking:
use admin
db.createUser(
{
user: "admin",
pwd: "password",
roles: [ { role: "root", db: "admin" } ]
}
)
The script above will create a super admin user. This type of user can manage access control such as adding other admin users and assign permissions per database.
Exit the mongo shell. In my case, ctrl + c
. Open MongoDB’s configuration file thru vi
. Any tool that you can edit it.
vi /etc/mongod.conf
Copy and append the script below to the opened mongod.conf
. Take note that this script is only applicable to MongoDB version 3.X and later.
If you have an older version, research for the correct script for your version or upgrade your MongoDB instance.
security:
authorization: enabled
Restart MongoDB to load the new configuration.
service mongod restart
If failed, try adding sudo
to the command.
If success, MongoDB is now running with authentication. Any application trying to connect will need to provide an account credentials on the connection string.
Set-up a user with assigned role/permission specific to your application’s needs. In my case, my database name is “myAppDB” and I need an account that has a read/write and read-only permission to it. With this said, reconnect to mongo shell as super admin user. Remember the user credentials we used on Step 2.
mongo --port 27017 -u admin -p password --authenticationDatabase admin
While in mongo shell, copy/paste the script below. Create the needed accounts from Step 5 by using the commmand below:
use myAppDB
db.createUser(
{
user: "readerWriter",
pwd: "password",
roles: [
{ role: "readWrite", db: "myAppDB" }
]
}
);
db.createUser(
{
user: "reader",
pwd: "password",
roles: [
{ role: "read", db: "myAppDB" }
]
}
);
The script above will create 2 users with different roles, readWrite
and read
. These are now the accounts I can use on my application’s connection string.
Using the readerWriter
account, I can update my connection string (see the start of this post) to this:
mongodb://readerWriter:password@localhost/myAppDB
However, If I want a read-only access to the database, I can use the reader
account:
mongodb://reader:password@localhost/myAppDB
Thanks for reading. :)