Question: How do you configure a MongoDB replica set with username and password authentication?

Answer

MongoDB supports role-based authentication to secure your database. To configure a MongoDB replica set with username and password authentication, follow the steps below:

Step 1: Enable Auth and Setup Initial Admin User

Initially, start your MongoDB instance without access control. Edit your mongod.conf file by adding or ensuring these lines exist for a standalone MongoDB server:

security: authorization: enabled replication: replSetName: \"rs0\"

Start your MongoDB server with this configuration. If it's a replica set, initiate it:

rs.initiate()

Connect to your MongoDB instance:

mongo

Create an initial admin user (in the admin database):

use admin db.createUser({ user: \"myAdminUser\", pwd: passwordPrompt(), // or \"<your password>\" roles: [ { role: \"userAdminAnyDatabase\", db: \"admin\" }, \"readWriteAnyDatabase\" ] })

Step 2: Restart the MongoDB Instance(s)

Restart your MongoDB instance(s) to have the changes take effect. Ensure that the security.authorization setting is enabled in your configuration file.

Step 3: Create Additional Users as Needed

After restarting, connect to the database using the admin account created:

mongo --username myAdminUser --password --authenticationDatabase admin

You can now create additional users with specific roles for different databases. For example, to create a user for your myappdatabase:

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

Step 4: Connect to the Replica Set with Authentication

When connecting to your replica set, use the credentials of the user who has permission on the database you're trying to access. Here's how you would connect from the mongo shell:

mongo --username appUser --password <appUserPassword> --authenticationDatabase myappdatabase --host rs0/host1:27017,host2:27017,host3:27017

In application connection strings, specify the username, password, and authentication database as well:

mongodb://appUser:<appUserPassword>@host1:27017,host2:27017,host3:27017/myappdatabase?authSource=myappdatabase&replicaSet=rs0

These steps ensure that your MongoDB replica set is secured with username and password authentication, allowing only authorized users to access or modify data.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.