Overview
In this guide, you can learn how to authenticate with MongoDB using each authentication mechanism available in the MongoDB Community Edition. Authentication mechanisms are processes by which the driver and MongoDB deployment confirm identity and establish trust to ensure security.
The mechanisms that you can use with the latest version of MongoDB Community Edition are as follows:
To authenticate using Kerberos or LDAP, see the
Enterprise Authentication Mechanisms guide.
For more information about establishing a connection to your MongoDB cluster,
see the Connect to MongoDB guide.
Specify an Authentication Mechanism
You can specify your authentication mechanism and credentials when connecting to MongoDB using either of the following:
A connection string
A
MongoCredentialfactory method
A connection string (also known as a connection uri) specifies how to connect and authenticate to your MongoDB cluster.
To authenticate using a connection string, include your settings in your
connection string and pass it to the MongoClients.create() method to
instantiate your MongoClient. Select the Connection String
tab to see the syntax for authenticating using a connection string.
Alternatively, you can use the MongoCredential class to specify your
authentication details. The MongoCredential class contains static factory
methods that construct instances containing your authentication mechanism and
credentials. When you use the MongoCredential helper class, you need
to use the MongoClientSettings.Builder class to configure your
connection settings when constructing your MongoClient. Select the
MongoCredential tab to see the syntax for authenticating using a
MongoCredential.
For more information about these classes and methods, see the following API documentation:
Mechanisms
Default
The default authentication mechanism setting uses one of the following authentication mechanisms depending on what your version of MongoDB Server supports:
SCRAM-SHA-256SCRAM-SHA-1MONGODB-CR
Server versions 3.6 and earlier use MONGODB-CR as the default
mechanism. Newer versions of MongoDB Server use one of the mechanisms for
which they advertise support.
The following code snippets show how to specify the authentication mechanism, using the following placeholders:
username: your MongoDB usernamepassword: your MongoDB user's passwordhostname: network address of your MongoDB deployment that your client can accessport: port number of your MongoDB deploymentauthenticationDb: MongoDB database that contains your user's authentication data
Note
If you omit the authenticationDb parameter, the driver uses the
default admin database.
Select the Connection String or the MongoCredential tab below for instructions and sample code for specifying this authentication mechanism:
To specify the default authentication mechanism using a connection
string, omit the mechanism. The code to instantiate a MongoClient
resembles the following:
MongoClient mongoClient = MongoClients.create("mongodb://<db_username>:<db_password>@<hostname>:<port>/?authSource=<authenticationDb>");
To specify the default authentication mechanism using the
MongoCredential class, use the createCredential() method. The
code to instantiate a MongoClient resembles the following:
MongoCredential credential = MongoCredential.createCredential("<db_username>", "<authenticationDb>", "<db_password>"); MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() .applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress("<hostname>", <port>)))) .credential(credential) .build());
For more information about the challenge-response (CR) and salted challenge-response authentication mechanisms (SCRAM) that MongoDB supports, see the SCRAM section of the MongoDB Server manual.
SCRAM-SHA-256
Note
SCRAM-SHA-256 is the default authentication method for MongoDB starting
in MongoDB 4.0.
SCRAM-SHA-256 is a salted challenge-response authentication mechanism
(SCRAM) that uses your username and password, encrypted with the SHA-256
algorithm, to authenticate your user.
The following code snippets show how to specify the authentication mechanism, using the following placeholders:
username: your MongoDB usernamepassword: your MongoDB user's passwordhostname: network address of your MongoDB deployment that your client can accessport: port number of your MongoDB deploymentauthenticationDb: MongoDB database that contains your user's authentication data
Note
If you omit the authenticationDb parameter, the driver uses the
default admin database.
Select the Connection String or the MongoCredential tab below for instructions and sample code for specifying this authentication mechanism:
To specify the SCRAM-SHA-256 authentication mechanism using a
connection string, assign the authMechanism parameter the value
SCRAM-SHA-256 in your connection string. The code to instantiate
a MongoClient resembles the following:
MongoClient mongoClient = MongoClients.create("mongodb://<db_username>:<db_password>@<hostname>:<port>/?authSource=<authenticationDb>&authMechanism=SCRAM-SHA-256");
To specify the default authentication mechanism using the
MongoCredential class, use the
createScramSha256Credential()
method. The code to instantiate a MongoClient resembles
the following:
MongoCredential credential = MongoCredential.createScramSha256Credential("<db_username>", "<authenticationDb>", "<db_password>"); MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() .applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress("<hostname>", <port>)))) .credential(credential) .build());
SCRAM-SHA-1
Note
SCRAM-SHA-1 is the default authentication method for MongoDB versions
3.0, 3.2, 3.4, and 3.6.
SCRAM-SHA-1 is a salted challenge-response mechanism (SCRAM) that uses your
username and password, encrypted with the SHA-1 algorithm, to authenticate
your user.
The following code snippets show how to specify the authentication mechanism, using the following placeholders:
username: your MongoDB usernamepassword: your MongoDB user's passwordhostname: network address of your MongoDB deployment that your client can accessport: port number of your MongoDB deploymentauthenticationDb: MongoDB database that contains your user's authentication data
Note
If you omit the authenticationDb parameter, the driver uses the
default admin database.
Select the Connection String or the MongoCredential tab below for instructions and sample code for specifying this authentication mechanism:
To specify the SCRAM-SHA-1 authentication mechanism using a
connection string, assign the authMechanism parameter the value
SCRAM-SHA-1 in your connection string. The code to instantiate
a MongoClient resembles the following:
MongoClient mongoClient = MongoClients.create("mongodb://<db_username>:<db_password>@<hostname>:<port>/?authSource=<authenticationDb>&authMechanism=SCRAM-SHA-1");
To specify the default authentication mechanism using the
MongoCredential class, use the
createScramSha1Credential()
method. The code to instantiate a MongoClient resembles the following:
MongoCredential credential = MongoCredential.createScramSha1Credential("<db_username>", "<authenticationDb>", "<db_password>"); MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() .applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress("<hostname>", <port>)))) .credential(credential) .build());
MONGODB-CR
MONGODB-CR is a challenge-response authentication mechanism that uses your
username and password to authenticate your user. This authentication
mechanism was deprecated starting in MongoDB 3.6 and is no longer
supported as of MongoDB 4.0.
You cannot specify this method explicitly; refer to the fallback provided
by the default authentication mechanism to
connect using MONGODB-CR.
MONGODB-AWS
Note
The MONGODB-AWS authentication mechanism is available for MongoDB deployments on MongoDB Atlas.
The MONGODB-AWS authentication mechanism uses your Amazon Web Services
Identity and Access Management (AWS IAM) credentials to authenticate your
user. To learn more about configuring MongoDB Atlas, see the
Set Up Passwordless Authentication with AWS IAM Roles
guide.
To instruct the driver to use this authentication mechanism, you can specify
MONGODB-AWS either as a parameter in the connection string or by using
the MongoCredential.createAwsCredential() factory method.
Learn how to specify this authentication mechanism and the various ways to provide your AWS IAM credentials in the next sections.
These sections contain code examples that use the following placeholders:
awsKeyId: value of your AWS access key IDawsSecretKey: value of your AWS secret access keyatlasUri: network address of your MongoDB Atlas deploymenthostname: hostname of your MongoDB Atlas deploymentport: port of your MongoDB Atlas deploymentawsSessionToken: value of your AWS session token
AWS SDK for Java
New in version v4.8.
You can use one of the AWS SDK for Java v1 or v2 to specify your credentials. This method offers the following features:
Multiple options for obtaining credentials
Credential caching which helps your application avoid rate limiting
Credential provider management for use with the Elastic Kubernetes Service.
To use the AWS SDK for Java for MONGODB-AWS authentication, you must
perform the following:
Specify the authentication mechanism
Add the SDK as a dependency to your project
Supply your credentials using one of the methods in the credential provider chain
Important
This method of providing MONGODB-AWS credentials is available
only in the MongoDB Java Driver v4.8 and later.
To specify the authentication mechanism by using a MongoCredential,
use the MongoCredential.createAwsCredential() factory method
and add the MongoCredential instance to your MongoClient as shown
in the following example:
MongoCredential credential = MongoCredential.createAwsCredential(null, null); // Creates a MongoClient that receives configuration information from a MongoCredential and environment variables MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() .applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress("<hostname>")))) .credential(credential) .build());
To specify the authentication mechanism in the connection string, add it as a parameter as shown in the following example:
MongoClient mongoClient = MongoClients.create("mongodb://<atlasUri>?authMechanism=MONGODB-AWS");
To add the AWS SDK as a dependency to your project, see the following AWS documentation for the version you need:
For the AWS SDK for Java v2, see the Setting Up guide.
For the AWS SDK for Java v1, see the Getting Started guide.
Note
For the AWS SDK for Java v2, the Java driver currently tests using the
software.amazon.awssdk:auth:2.18.9 dependency.
For the AWS SDK for Java v1, the Java driver currently tests using the
com.amazonaws:aws-java-sdk-core:1.12.337 dependency.
To supply your credentials, see the following AWS documentation for the version you need:
To learn more about the AWS SDK for Java v2 class the driver uses to get the credentials, see the DefaultCredentialsProvider API documentation.
Learn how to supply your credentials to this class from the Use the default credential provider chain section.
To learn more about the AWS SDK for Java v1 class the driver uses to get the credentials, see the DefaultAWSCredentialsProviderChain API documentation.
Learn how to supply your credentials to this class from the Using the Default Credential Provider Chain section.
Note
If you include both v1 and v2 of the AWS SDK for Java in your project, you must use the v2 methods to supply your credentials.
Specify Your Credentials in the Environment
You can provide your AWS IAM credentials by instructing the driver to
use the MONGODB-AWS authentication mechanism and by setting the
appropriate environment variables.
To use the environment variables to supply your credentials, you must perform the following:
Specify the authentication mechanism
Add the appropriate environment variables
You can specify the authentication mechanism by using a MongoCredential
or on the connection string.
To specify the authentication mechanism by using a MongoCredential,
use the MongoCredential.createAwsCredential() factory method and add the
MongoCredential instance to your MongoClient as shown in the following
example:
MongoCredential credential = MongoCredential.createAwsCredential(null, null); // Creates a MongoClient that receives configuration information from a MongoCredential and environment variables MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() .applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress("<hostname>")))) .credential(credential) .build());
To specify the authentication mechanism in the connection string, add it as a parameter as shown in the following example:
MongoClient mongoClient = MongoClients.create("mongodb://<atlasUri>?authMechanism=MONGODB-AWS");
The next examples show how to provide your credentials by setting environment variables for the following types of authentication:
Programmatic access keys
Web identity provider
ECS container credentials
EC2 container credentials
The following example shows how you can set your programmatic access keys
in environment variables by using bash or a similar shell:
export AWS_ACCESS_KEY_ID=<awsKeyId> export AWS_SECRET_ACCESS_KEY=<awsSecretKey> export AWS_SESSION_TOKEN=<awsSessionToken>
Omit the line containing AWS_SESSION_TOKEN if you don't need an AWS
session token for that role.
You can use an OpenID Connect (OIDC)-compatible web identity provider to authenticate to Amazon Elastic Kubernetes Service (EKS) or other services.
Important
Your project must include v1 or v2 of the AWS SDK as a dependency to authenticate using a web identity provider.
To use a web identity provider, create a file that contains your
OIDC token. Next, use bash or a similar shell to set an environment variable
to the absolute path to this file, as shown in the following example:
export AWS_WEB_IDENTITY_TOKEN_FILE=<absolute path to file containing your OIDC token>
To authenticate by using ECS container credentials, set the ECS
endpoint relative URI in an environment variable by using bash or
a similar shell as shown in the following example:
export AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=<your ECS endpoint>
To authenticate by using EC2 container credentials, make sure none of the environment variables mentioned in this section are set. The driver obtains the credentials from the default IPv4 EC2 instance metadata endpoint instead of from environment variables.
Specify Your Credentials in a MongoCredential
You can supply your AWS IAM credentials to a MongoClient by using a
MongoCredential instance. To construct the MongoCredential instance
for MONGODB-AWS authentication, use the createAwsCredential()
factory method.
You can supply only programmatic access keys to the
MongoCredential.createAwsCredential() method. If you must supply ECS
or EC2 container credentials, use the instructions in
Specify Your Credentials in the Environment or AWS SDK for Java.
To use the MongoCredential for MONGODB-AWS authentication, you
must perform the following:
Specify the authentication mechanism
Supply the credentials
To specify the authentication mechanism by using a MongoCredential,
use the MongoCredential.createAwsCredential() factory method
and add the MongoCredential instance to your MongoClient as shown
in the following example:
MongoCredential credential = MongoCredential.createAwsCredential("<awsKeyId>", "<awsSecretKey>".toCharArray()); // Creates a MongoClient that receives AWS credentials from the MongoCredential instance MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() .applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress("<hostname>")))) .credential(credential) .build());
If you must specify an AWS session token, pass it to the withMechanismProperty() method as shown in the following example:
MongoCredential credential = MongoCredential.createAwsCredential("<awsKeyId>", "<awsSecretKey>".toCharArray()).withMechanismProperty("AWS_SESSION_TOKEN", "<awsSessionToken>"); // Creates a MongoClient that receives configuration information from a MongoCredential instance MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() .applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress("<hostname>")))) .credential(credential) .build());
To refresh your credentials, you can declare a Supplier lambda expression
that returns new credentials as shown in the following example:
Supplier<AwsCredential> awsFreshCredentialSupplier = () -> { // Add your code to fetch new credentials return new AwsCredential("<awsKeyId>", "<awsSecretKey>", "<awsSessionToken>"); }; // Creates a MongoCredential instance to specify the new AWS credentials MongoCredential credential = MongoCredential.createAwsCredential(null, null) .withMechanismProperty(MongoCredential.AWS_CREDENTIAL_PROVIDER_KEY, awsFreshCredentialSupplier); // Creates a MongoClient that receives new configuration information from a MongoCredential instance MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() .applyToClusterSettings(builder -> builder.hosts(Collections.singletonList(new ServerAddress("<hostname>", <port>)))) .credential(credential) .build());
Note
If you must provide AWS IAM credentials in a connection string, refer to a previous release of the MONGODB-AWS driver documentation.
X.509
The X.509 authentication mechanism uses
TLS with X.509 certificates to
authenticate your user, identified by the relative distinguished names
(RDNs) of your client certificate. When you specify the X.509
authentication mechanism, the server authenticates the connection using
the subject name of the client certificate.
The following code snippets show how to specify the authentication mechanism, using the following placeholders:
hostname: network address of your MongoDB deployment that your client can accessport: port number of your MongoDB deploymentauthenticationDb: MongoDB database that contains your user's authentication data
Note
If you omit the authenticationDb parameter, the driver uses the
default admin database.
Select the Connection String or the MongoCredential tab below for instructions and sample code for specifying this authentication mechanism:
To specify the X.509 authentication mechanism using a connection
string, assign the authMechanism parameter the value MONGODB-X509
and enable TLS by assigning the tls
parameter a true value. The code to instantiate a MongoClient
resembles the following:
MongoClient mongoClient = MongoClients.create("mongodb://<hostname>:<port>/?authSource=<authenticationDb>&authMechanism=MONGODB-X509&tls=true");
To specify the X.509 authentication mechanism using the
MongoCredential class, use the
createMongoX509Credential()
method. Also, enable TLS by calling the
applyToSslSettings()
method and setting the enabled property to true in the
SslSettings.Builder
block. The code to instantiate a MongoClient resembles
the following:
MongoCredential credential = MongoCredential.createMongoX509Credential(); MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() .applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress("<hostname>", <port>)))) .applyToSslSettings(builder -> builder.enabled(true); ) .credential(credential) .build());
To learn more about configuring your application to use certificates as well as TLS/SSL options, see the Enable TLS/SSL on a Connection guide.