DEV Community

Cover image for MongoDB Access Control: Creating Secure Users with Custom Roles
Hemanth Babu
Hemanth Babu

Posted on

MongoDB Access Control: Creating Secure Users with Custom Roles

🔐 MongoDB Access Control: Creating Secure Users with Custom Roles

TL;DR:

  • ✅ Create an admin user with full privileges
  • 🧱 Define custom roles for specific collections
  • 👥 Assign roles to users per database
  • 🔒 Enable access control in MongoDB config
  • 🔗 Use correct connection strings with authSource

🚀 Why MongoDB Access Control Matters

Security isn't optional—especially when you're dealing with databases that store critical application data. MongoDB, one of the most popular NoSQL databases, offers powerful access control mechanisms that let you define who can do what—right down to the collection level.

In this guide, you'll learn how to set up user-based authentication and custom roles to secure your MongoDB deployment like a pro. Whether you're managing dev environments or preparing for production, this setup will help you sleep better at night.


🛠️ Step-by-Step: Setting Up Access Control in MongoDB

🔑 1. Create the Admin User

Let’s begin with setting up an admin user who has the power to manage users and roles across all databases.

use admin

db.createUser({
  user: "myUserAdmin",
  pwd: passwordPrompt(),
  roles: [
    { role: "userAdminAnyDatabase", db: "admin" },
    { role: "readWriteAnyDatabase", db: "admin" }
  ]
})
Enter fullscreen mode Exit fullscreen mode

💡 The userAdminAnyDatabase role allows this user to create, modify, and assign roles across all databases.


🧱 2. Define a Custom Role (Fine-Grained Access Control)

Want to allow users access only to specific collections like products and orders? Create a user-defined role tailored to those needs.

use mydb;

db.createRole({
  role: "editor",
  privileges: [
    {
      resource: { db: "mydb", collection: "products" },
      actions: ["find", "insert", "update", "remove"]
    },
    {
      resource: { db: "mydb", collection: "orders" },
      actions: ["find", "insert", "update", "remove"]
    }
  ],
  roles: [] // Inherited roles (leave empty if none)
})
Enter fullscreen mode Exit fullscreen mode

🧠 Think of this like giving someone keys to just two rooms in a building—not the whole building.


👤 3. Assign the Role to a User

✅ Option A: Create the User (if they don’t exist yet)

use mydb

db.createUser({
  user: "myUser",
  pwd: passwordPrompt(),
  roles: [
    { role: "editor", db: "mydb" },
    { role: "read", db: "reporting" }
  ]
})
Enter fullscreen mode Exit fullscreen mode

🔄 Option B: Update an Existing User

use mydb;

db.updateUser("myUser", {
  roles: [
    { role: "editor", db: "mydb" }
  ]
})
Enter fullscreen mode Exit fullscreen mode

🔐 Roles are assigned per database, so always specify both the role and the target DB.


🧪 4. Verify Users and Roles

Before moving forward, it’s good practice to check that everything is set up correctly.

use admin;

db.getUsers();
db.getRoles();
Enter fullscreen mode Exit fullscreen mode

Use this to confirm that the users and their assigned roles appear as expected.


⚙️ 5. Enable Access Control in MongoDB Config

This step locks the door and turns on the bouncer. Modify your MongoDB configuration file:

Path: C:\\Program Files\\MongoDB\\Server\\8.0\\bin\\mongod.cfg

# Security section
security:
  authorization: enabled
Enter fullscreen mode Exit fullscreen mode

📁 After saving the file, restart your MongoDB service for changes to take effect.


🔗 6. Connect with Authenticated Access

Here’s how your MongoDB URI looks when connecting with credentials:

mongodb://myUser:myPassword@localhost:27017/mydb?authSource=mydb
Enter fullscreen mode Exit fullscreen mode

Notice the authSource=mydb? That’s telling MongoDB where to verify credentials.


🎯 Conclusion: Lock It Down Like a Pro

By now, you’ve:

  • Created an admin user
  • Defined custom roles
  • Assigned those roles to users
  • Enabled authentication
  • Verified and connected securely

This setup gives you tight control over who can access what in your database. Whether you're building a multi-user app or just locking down a staging server, these best practices put security front and center.


💬 What’s Next?

What other MongoDB topics would you like to see covered? Maybe role inheritance, replica set authentication, or integration with external identity providers? Let’s continue the conversation—drop your thoughts in the comments below!

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.