Installing MongoDB
This article assumes that we will be installing MongoDb on Ubuntu 14.04.
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org
Enable authentication
First, create an admin user. This user will only be able to login locally:
use admin db.createUser( { user: "admin", pwd: "password", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] } )
Next, we need to enable auth by uncommenting the line auth=enabled
in the /etc/mongo.conf file, and then restarting the mongo service:
vi /etc/mongod.conf
sudo service restart mongod
Setup Database users
Now that auth has been abled, you can create specific users with role based access to each specific database. First, login using the mongo CLI:
mongo localhost/admin -u admin -p password
Then, you can create your user by selecting your database, and replacing the values for the document below:
use yourdb db.createUser( { user: "yourdbadmin", pwd: "supersecret", roles: [ { role: "dbOwner", db: "yourdb" } ] } )
Read about Mongo’s built in roles here: http://docs.mongodb.org/manual/reference/built-in-roles/
Test your connection from a remote server
mongo yourserver.com/yourdb -u yourdbadmin -p supersecret