MongoDB Authentication

Learn the MongoDB authentication methods and the requirements needed to properly authenticate a user in MongoDB.

MongoDB is a modern general purpose database that often involves highly sensitive and mission-critical data. Authentication -- the process of verifying the identity of a user -- is therefore one of the most important and central features of MongoDB.

The main purposes of authentication are:

  • Requiring that all clients and servers provide valid credentials to connect to the system.
  • Restricting users to only perform actions as determined by their roles.
  • Allowing tracking system events (e.g., user classification, audit on login information) on MongoDB instances.
  • Permitting forensic analysis and allowing administrators to verify proper controls.

MongoDB Authentication Mechanisms

MongoDB Atlas comes with built-in TLS and the latest authentication abilities, like SCRAM, X.509, AWS IAM, and LDAP integrations. It allows an easy UI or API setup.

To secure your deployments, you must apply at least one of the following mechanisms.

Each of these mechanisms has its benefits and use cases.

  • SCRAM (Default)

    SCRAM, which is also known as Salted Challenge Response Authentication Mechanism, adheres to the best practices set out in RFC 5802, which defines standards for authenticating users with a challenge-response mechanism. It is commonly referred to as username/password authentication and can use SHA-1 or SHA-256 algorithms.

  • x.509 Certificate Authentication

    MongoDB supports X.509 certificate authentication for use with a secure TLS connection. The X.509 certificate allows clients to authenticate to servers with certificates rather than with a username and password.

  • LDAP Proxy Authentication (Only for MongoDB Enterprise and Atlas)

    MongoDB Enterprise supports federated SSO authentication of users. This allows administrators to configure a MongoDB cluster to authenticate users by proxying authentication requests to a specified LDAP service.

  • Kerberos Authentication (Only for MongoDB Enterprise)

    MongoDB Enterprise supports authentication using a Kerberos service. Kerberos is an IETF (RFC 4120) standard authentication protocol for large client/server systems.

How to Add Authentication to MongoDB

MongoDB Atlas requires any user connecting to the cluster to be authenticated via one of the available mechanisms.

If you wish to add more mechanisms, you need to create database users with the additional mechanism (SCRAM, X.509, AWS IAM, or LDAP).

With a self-managed deployment, you need the following guide to add the needed configuration and users to your deployment.

How to Enable Authentication in MongoDB

To enable authentication in MongoDB, we first need to create an administrator account.

  1. Start MongoDB without authentication (default no authentication configuration).
  2. Connect to the server using the mongo shell from the server itself.

    $ mongo mongodb://localhost:<port>

    Note: The port is usually set to 27017.

  1. Create an administrator in the admin database with a userAdminAnyDatabase role. This role provides the ability to create and modify roles and users on the current database except local and config.

    MongoDB Authorization grants access to data and commands through role-based authorization. In MongoDB Authorization, Privilege is either specified explicitly in the role or inherited from another role, or both. MongoDB allows us to create new user roles for particular databases if we think that the existing built-in roles to control access to a MongoDB system do not describe the set of desired privileges. In addition, you can also create Superuser roles that provide either direct or indirect system-wide superuser access.

    In the following example, we will create an Admin user with myNewPassword as a password.

    > use admin
    > db.createUser(
    user: "Admin",
    pwd: "myNewPassword",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  2. Disconnect from the mongo shell (Ctrl+D).
  3. Locate the following code in the mongod configuration file (/etc/mongod.conf).

    authorization: "disabled"
  4. Change authorization disabled to enabled and save the file.

    authorization: "enabled"
  5. Restart MongoDB using the following code.

    sudo service mongodb restart

Once this is complete, all the clients trying to connect to this server must authenticate the user with SCRAM default authentication mechanism.

How to Authenticate Users in MongoDB

To authenticate Atlas users, please follow the connection instructions on your cluster connect dialog.

To authenticate as a user, you must provide a username, password, and the authentication database associated with that user.

To authenticate using the mongo shell, either:

  1. Connect first to the MongoDB or mongos instance.

    $ mongo mongodb://<host>:<port>
  1. Run the authenticate command or the db.auth() method against the authentication database.

    > db.auth("Admin", "myNewPassword","SCRAM-SHA-1",false)

    Note: db.auth() returns 0 when authentication is not successful, and 1 when the operation is successful.


  1. Connect and authenticate in one single step. This step is not recommended because it will leave your credentials visible in your terminal history, which can be exploited by any program in your computer. We can use an environment variable to hide our password:

    mongo "mongodb://Admin:${DBPASSWORD}@<host>:<port>/admin?authSource=admin"

How to Create New Users in MongoDB

MongoDB Atlas allows creating users via the UI or API as well as adding built-in roles or creating custom roles. There are some limitations to the number of users per project. Those may be extended only by contacting MongoDB Atlas support.

When you self-manage the database, you can use the db.createUser() method to create a user in the authentication database. Administrators can assign any built-in or user-defined roles to the new user. Although authentication is strongly coupled with authorization, they are not the same and each requires a deeper consideration when designing your database security.

Note: A user’s credentials will be stored in one authentication database. The user can also have privileges across multiple different databases. By assigning to the user roles in other databases, a user created in one database can have permission to act on other databases.

In the following code excerpt, we are trying to add a new user justAUser to the demo database. This new user will also get a readWrite role in the demo database. We will also give the user a read role in the finances database.

use demo
    user: "justAUser",
    pwd:  passwordPrompt(),   // or cleartext password
    roles: [ { role: "readWrite", db: "demo" },
             { role: "read", db: "finances" } ]

What to Do if MongoDB Authentication Fails

When your authentication fails, it's important to understand the root cause of the failure. MongoDB Atlas provides a detailed authentication and connection troubleshooting page.

Let's show some possible failures:

  • Wrong username/password, resulting in Error: Authentication failed..

    • Logs:

    {"t":{"$date":"2021-05-03T10:30:18.099+03:00"},"s":"I",  "c":"ACCESS",   "id":20249,   "ctx":"conn11","msg":"Authentication failed","attr":{"mechanism":"SCRAM-SHA-1","principalName":"user","authenticationDatabase":"admin","client":"","result":"AuthenticationFailed: SCRAM authentication failed, storedKey mismatch"}}
  • Wrong authentication database, resulting in Error: Authentication failed..

    • Logs:

    {"t":{"$date":"2021-05-03T10:29:24.324+03:00"},"s":"I",  "c":"ACCESS",   "id":20249,   "ctx":"conn10","msg":"Authentication failed","attr":{"mechanism":"SCRAM-SHA-1","principalName":"user","authenticationDatabase":"test","client":"","result":"UserNotFound: Could not find user \"user\" for db \"test\""}}


MongoDB Atlas and MongoDB Server provide a variety of authentication mechanisms that allow users to secure their deployment, from a simple username/password authentication to a full enterprise-grade authentication mechanism, like LDAP and Kerberos.

It's important to familiarize yourself with these mechanisms and make sure you secure your data properly.


How do I authenticate to MongoDB?

You will need to provide the set of credentials and an authentication source (admin, $external etc.), depending on the authentication mechanism, to the relevant connecting client (Driver, Shell, Compass etc.).

What is database authentication in MongoDB?

It's the ability to secure the database and restrict access if a user cannot provide a set of valid credentials to the server.

How do I enable authentication in MongoDB Windows?

Following the generic guides should be sufficient for a Windows Operating System. Make sure to check if there are any specific notes for Windows.

How do I log in as an admin in MongoDB?

Using a user with built-in admin roles or superuser privileges will allow you admin access. For Atlas deployments, you have an atlasAdmin role.

How do I find my MongoDB username and password?

You can view users’ information when issuing the db.getUsers() command. However, the cleartext password is never stored in the database. Therefore, you can only change it by running db.changeUserPassword(<user>,<newPassword>) . In Atlas, this can be done via the Database Users UI or API.

How do I access MongoDB remotely?

To access MongoDB remotely, we need to provide the connecting client a resolvable IP or DNS to our deployment hosts with the relevant ports to reach that deployment. Additionally, we need to provide credentials as part of this client connection attempt to finally access the database data.

How secure is MongoDB?

If you follow our security checklist, which is the standard in our Atlas clusters, and implement our security recommendations, MongoDB is very secure. Our enterprise-grade security solutions are compliant to a large set of security compliance standards. Read more on our Trust Center.