Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

MongoDB Security — Authentication and RBAC

Why MongoDB Security Matters

By default, MongoDB does not enable authentication, which means any client that can connect to the server has full access. Securing your MongoDB deployment is critical before exposing it to any network. MongoDB provides a layered security model covering authentication, authorization, encryption, and auditing.

Enabling Authentication

Start mongod with the --auth flag to require all clients to authenticate. You should first create an admin user before enabling auth, otherwise you will be locked out.

Creating Admin User and Enabling Auth
// Step 1: Connect without auth (first time only)
mongosh

// Step 2: Switch to admin database
use admin

// Step 3: Create the root admin user
db.createUser({
  user: "adminUser",
  pwd: "StrongP@ssw0rd!",
  roles: [{ role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase"]
})

// Step 4: Exit and restart mongod with --auth
// mongod --auth --port 27017 --dbpath /data/db

// Step 5: Reconnect with credentials
mongosh --username adminUser --password StrongP@ssw0rd! --authenticationDatabase admin

Creating Database Users

Create dedicated users for each application with only the permissions they need. Never use the admin account for application connections.

Creating Application Database Users
use myapp

// Create a read-write user for the application
db.createUser({
  user: "appUser",
  pwd: "AppP@ss123!",
  roles: [{ role: "readWrite", db: "myapp" }]
})

// Create a read-only user for reporting
db.createUser({
  user: "reportUser",
  pwd: "ReportP@ss456!",
  roles: [{ role: "read", db: "myapp" }]
})

// List all users in the current database
db.getUsers()

// Update a user's password
db.changeUserPassword("appUser", "NewP@ss789!")

// Delete a user
db.dropUser("reportUser")

Role-Based Access Control (RBAC)

MongoDB uses RBAC to control what actions users can perform. Built-in roles cover most use cases:

RoleScopePermissions
readDatabaseRead all non-system collections
readWriteDatabaseRead and write all non-system collections
dbAdminDatabaseSchema, indexing, and statistics tasks
userAdminDatabaseCreate and modify users and roles
dbOwnerDatabaseAll admin, userAdmin, and readWrite combined
readAnyDatabaseGlobalRead access to all databases
readWriteAnyDatabaseGlobalRead/write access to all databases
userAdminAnyDatabaseGlobalManage users on all databases
clusterAdminGlobalFull cluster management (sharding, replication)
rootGlobalSuperuser - all privileges
Custom Roles and Role Management
use myapp

// Create a custom role with specific collection access
db.createRole({
  role: "ordersReadOnly",
  privileges: [
    {
      resource: { db: "myapp", collection: "orders" },
      actions: ["find"]
    }
  ],
  roles: []
})

// Assign the custom role to a user
db.createUser({
  user: "ordersViewer",
  pwd: "ViewerP@ss!",
  roles: [{ role: "ordersReadOnly", db: "myapp" }]
})

// Grant additional role to existing user
db.grantRolesToUser("appUser", [{ role: "dbAdmin", db: "myapp" }])

// Revoke a role from a user
db.revokeRolesFromUser("appUser", [{ role: "dbAdmin", db: "myapp" }])

Network Security - IP Binding and TLS/SSL

Restrict which network interfaces MongoDB listens on using bindIp, and encrypt data in transit using TLS/SSL. Never expose MongoDB directly to the public internet.

mongod.conf - Network and TLS Configuration
// mongod.conf (YAML format)
net:
  port: 27017
  bindIp: 127.0.0.1,10.0.0.5   // only listen on localhost and internal IP
  tls:
    mode: requireTLS
    certificateKeyFile: /etc/ssl/mongodb.pem
    CAFile: /etc/ssl/ca.pem

security:
  authorization: enabled

// Connect with TLS from mongosh
mongosh --tls \
  --tlsCertificateKeyFile /etc/ssl/client.pem \
  --tlsCAFile /etc/ssl/ca.pem \
  --host myserver.example.com \
  --username appUser \
  --authenticationDatabase myapp

Security Best Practices

  • Always enable --auth in production.
  • Use bindIp to restrict network access to trusted IPs only.
  • Enable TLS/SSL to encrypt data in transit.
  • Use strong, unique passwords for all database users.
  • Apply the principle of least privilege - grant only necessary roles.
  • Enable MongoDB auditing to track access and changes.
  • Use MongoDB's Client-Side Field Level Encryption (CSFLE) for sensitive fields.
  • Regularly rotate credentials and review user access.
  • Keep MongoDB updated to the latest stable version.
  • Use a firewall to block port 27017 from public access.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.