Secure MongoDB Self-Managed: AuthN and AuthZ / Configure Authentication and Authorization

Code Summary: Self-Managed MongoDB Authentication

The code below activates authentication, authorization, and creates a new user.

Enable Authentication and Authorization:

Update the mongod.conf file with the following:

security:
    authorization: enabled

NOTE: After updating the mongod config file you need to restart the mongod process.

Create a new database user:

Connect to your MongoDB deployment using the localhost exception and run the following:

use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: passwordPrompt(), // or cleartext password
    roles: [
      { role: "userAdminAnyDatabase", db: "admin" },
      { role: "readWriteAnyDatabase", db: "admin" }
    ]
  }
)