0

I am utilizing MongoDB as a database platform into my application. As a security measure I need to allow my database to be accessible only from my server. Looking forward for appropriate solution.

3

You have to enable MongoDB access control. This uses a bindIp value in the mongod.conf file that by default listens to connections locally (e.g. bindIp:127.0.0.1 or with another local address, bindIP:127.0.0.1,10.0.0.10).

For that, you will need to create an admin or root user by doing this:

use admin
db.createUser(
  {
    user: "root",
    pwd: "abc123",
    roles: [ { role: "root", db: "admin" } ]
  }
)

Something similar you will need to do to create a user for your application:

use appDatabase
db.createUser(
  {
    user: "appUser",
    pwd: "appUserPassword",
    roles: [ { role: "readWrite", db: "appDatabase" } ]
  }
)

Then, in your mongod.conf file (in a CentOS server is located at /etc/mongod.conf), do the following:

  • Uncomment 'security'.
  • Add below it 'authorization: enable' (keep authentication commented out).
  • Make sure the bindIp value is set to 127.0.0.1

Then, when logged onto your server, if you need to connect to your MongoDB instance, do that with the admin/root user you just created:

mongo -u root -p --authenticationDatabase admin

You should also make sure you can successfully log onto mongo with your appUser:

mongo -u appUser -p --authenticationDatabase appDatabase

From your application, you will need to connect with an URL similar to this one:

mongodb://appUser:appUserPassword@localhost:27017/appDatabase?authSource=appDatabase

Reference: MongoDB - Enable Authentication | MongoDB - Configuration File Options

  • In addition to limiting network exposure with bindIP (which should be the default in packaged installs of MongoDB 2.6+) and configuring access control (which is not set up by default), I would recommend enabling the O/S firewall and reviewing other measures as per the MongoDB Security Checklist: docs.mongodb.com/manual/administration/security-checklist. – Stennie Jan 8 '17 at 5:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.