MongoDB Authorization
Learn and practice how to enable authorization, create roles and users, and assign user roles on a database.
By default, a new MongoDB database doesn’t enable authorization, and has no users. MongoDB comes with default roles such as root
, userAdmin
, userAdminAnyDatabase
when we install it.
The root
is the superuser role that provides system-wide access to the user. It can also create custom roles using a combination of permissions.
To learn about authorization, we’ll create an admin user with the userAdminAnyDatabase
role. Authorization is not required for the development.
The userAdminAnyDatabase
role allows us to add or remove users for any database on MongoDB.
Create a new user
We use the below steps to create a new user in MongoDB.
- We use the MongoDB Shell tool, shown in code as
mongosh
, to connect to MongoDB.
mongosh
Throughout this course, mongosh
is always running in a terminal by default.
- We switch to the
admin
database. By default, thetest
database is selected.
use admin
- We create an admin user.
Below is the syntax to create a MongoDB user.
db.createUser({
createUser: "<username>",
pwd: Password,
roles: [Role, ...],
});
// You can provide either plain text or
prompt when the command is executed.
Password = passwordPrompt() || "<password plain
...