By default, authentication is disabled in MongoDB, but this is not so critical as, out of the box, MongoDB is listening on localhost
only.
If you are going to allow remote connections to MongoDB, then it is definitely needed to enable authentication.
In the following article i will show how to enable authentication in MongoDB and how to create admin
and root
users.
Read more: Allow remote access to MongoDB
Create Admin/Root User in MongoDB
Connect to MongoDB using mongo
shell:
$ mongo
Authentication Database: In MongoDB, user can have privileges across different databases. When adding a user, you create the user in a specific database. This database is the authentication database for this user.
Switch to admin
database:
> use admin
Create mongo-admin
user:
> db.createUser( { user: "<strong>mongo-admin</strong>", pwd: "<strong>passw0rd</strong>", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] } )
Create mongo-root
user:
> db.createUser( { user: "mongo-root", pwd: "passw0rd", roles: [ { role: "root", db: "admin" } ] } )
Admin vs Root: The role userAdminAnyDatabase in MongoDB gives ability to create users and assign roles to them, but by itself it doesn’t allow the user to do anything else. The superuser role in MongoDB is the root.
Enable Authentication in MongoDB
Open MongoDB configuration file /etc/mongod.conf
and enable auth:
security: authorization: "enabled"
Restart mongod
to apply modifications:
$ sudo service mongod restart
As only authentication is enabled, you won’t be able to execute MongoDB commands without being authenticated:
“errmsg” : “command listDatabases requires authentication”,
“code” : 13,
“codeName” : “Unauthorized”
Switch to the authentication database (in our case, admin
) and authenticate:
> use admin > db.auth("mongo-admin", "passw0rd" ) - or - > db.auth("mongo-root", "passw0rd" )
Source: MongoDB: Auth – Enable Authentication – Create Admin/Root User