Setup MongoDB with Authentication and connect using mongoose
Setting up MongoDB is quite easy. On the other hand securing MongoDB is quite challenging. But after this tutorial it shouldn’t be.
In this tutorial, we will setup MongoDB with authentication and connect to it using Mongoose.
Due to the challenges involved in securing MongoDB a lot of the times I have seen developers tend to casually run MongoDB without authentication, even on production environments. This is a big security risk and should never be done.
A point to note is that, installtion of MongoDB will differ depending on your operating system, but steps for enabling authentication will remain same.
For this tutorial, I’ll be setting up MongoD on ubuntu. But as I said if you are here for Securing MongoDB then it
So let’s begin by installing MongoDB
Import the public Key
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4
Create a list file. Depending on your Ubuntu version execute the appropriate command.
## Ubuntu 18
echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list
## Ubuntu 16
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list
## Ubuntu 14
echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list
Next, reload the local package database
sudo apt-get update
Finally install it by running..
sudo apt-get install -y mongodb-org
Starting MongoDB
sudo service mongod start
In windows you would just run mongod via command prompt to start it.
Enabling User Authentication and authorization in MongoDB
Now that the easy part of the tutorial is done, let’s get on with the real stuff. We will secure our MongoDB installation, the steps would remain the same irrespective of the operating system.
By default, MongoDB is installed without any authentication, but we can enable it by creating a user with a role. Considering
Once connected to the Mongo shell add a user to the admin database.
use admin
db.createUser(
{
user: "admin",
pwd: "admin123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)
With the above statement, we have created a user named admin. MongoDB supports Role-based access control, So here the role specifies the role and the
The DB in which the user is created will be the authentication database for that user.
Now we need to restart MongoDB with auth enabled. In windows you can just do that by running ..
mongod --auth
Whereas if you are on Linux, it would be better to enable it in the config file.
Open /etc/mongod.conf and change the security section to look like this
security:
authorization: "enabled"
Save the file and restart mongod service.
sudo service mongod restart
Now if you try to connect to mongo shell without authentication it would still connect but you won’t be able to do anything except using a database.
To connect using auth in Mongo shell we will have to pass the username, password and authentication database for that user, as shown below.
mongo -u "admin" -p "admin123" --authenticationDatabase "admin"
To get the list of predefined roles and privileges run…
use admin
db.getRoles(
{
rolesInfo: 1,
showPrivileges:true,
showBuiltinRoles: true
}
)
Connecting to Auth enabled MongoDB with Mongoose
Connecting to auth enabled MongoDB in Node.js using Mongoose it a bit different as compared to simply connecting an unauthenticated one where you just specify the connection string.
const mongoose = require('mongoose');
const mongoURI = "mongodb://localhost:27017/ciphertrick?authSource=admin"; //connecting to ciphertrick
const options = {
user:"admin",
pass:"admin123",
keepAlive: true,
keepAliveInitialDelay: 300000,
useNewUrlParser: true
};
mongoose.connect(mongoURI, options);
mongoose.connection.on('connected', ()=>{
console.log('Mongoose default connection open to ' + mongoURI);
});
// If the connection throws an error
mongoose.connection.on('error', (err)=>{
console.log('handle mongo errored connections: ' + err);
});
// When the connection is disconnected
mongoose.connection.on('disconnected', ()=>{
console.log('Mongoose default connection disconnected');
});
process.on('SIGINT', ()=>{
mongoose.connection.close(()=>{
console.log('App terminated, closing mongo connections');
process.exit(0);
});
});
If you have seen above we have passed the user and pass in options. We have also specified the authorization database as
Conclusion
In this lesson we have learnt to install MongoDB but more importantly we have learnt how to secure MongoDB by enabling authentication and authorization, we have also seen how we can connect to an authentication enabled MongoDB using Mongoose.
Leave a Comment