Search⌘ K
AI Features

Authentication, Authorization, and Common Errors

Explore how MongoDB secures access through authentication and authorization by managing user roles and permissions. Understand the steps to enable authentication, test user capabilities, and handle common errors such as validation, authentication, and authorization failures.

Authentication verifies the identity of a user (e.g., username and password). Whereas, authorization determines what actions an authenticated user is allowed to perform (based on roles and permissions). Authentication keeps unauthorized users out, and authorization limits what authenticated users can do.

Summary of the process
Summary of the process

How MongoDB handles authentication

By default, MongoDB may run without authentication (not recommended for production). We can enable authentication so users must log in before accessing the database. To enable authentication, we need to perform the following steps. Switch to the admin database to create an administrative user.

Javascript (babel-node)
mongosh admin

Note: Global roles like userAdminAnyDatabase, readWriteAnyDatabase, and dbAdminAnyDatabase

are defined only in the admin database.

Javascript (babel-node)
db.createUser({
user: "superadmin",
pwd: "securepass",
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
})
...