Home > AI > Database > MongoDB >

Enable Access Control

Step 1: add user admin

$ mongo

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

Step 2: restart mongo service

Mac

$ brew services list | grep mongodb
$ brew services stop mongodb-community
$ brew services start mongodb-community

CentOS

$ sudo service mongod start

Step 3: test if user admin can successfully login

$ mongo --authenticationDatabase "admin" -u "myUserAdmin" -p

Step 4: enable access control

Location of configuration

Linux/etc/mongod.conf
Mac/usr/local/etc/mongod.conf (on Intel processors), or
/opt/homebrew/etc/mongod.conf (on Apple M1 processors)
Windows\bin\mongod.cfg

Add this snippet to your config

security:
    authorization: enabled

Step 5: test if the authentication is enabled

$ mongo
$ show dbs

Then, you have two methods to access database:

Authenticate during Connection

$ mongo --port 27017  --authenticationDatabase "admin" -u "myUserAdmin" -p

Authenticate after Connection

$ mongo
> use admin
> db.auth("myUserAdmin", passwordPrompt()) // or cleartext password

Leave a Reply