Docs Menu
Docs Home
/ / /
Java Sync
/

Authentication Mechanisms

On this page

  • Overview
  • Specify an Authentication Mechanism
  • Mechanisms
  • Default
  • SCRAM-SHA-256
  • SCRAM-SHA-1
  • MONGODB-CR
  • MONGODB-AWS
  • X.509

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 on establishing a connection to your MongoDB cluster, read our Connection Guide.

You can specify your authentication mechanism and credentials when connecting to MongoDB using either of the following:

  • A connection string

  • A MongoCredential factory 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 on these classes and methods, refer to the following API documentation:

The default authentication mechanism setting uses one of the following authentication mechanisms depending on what your version of MongoDB Server supports:

  1. SCRAM-SHA-256

  2. SCRAM-SHA-1

  3. MONGODB-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 username

  • password - your MongoDB user's password

  • hostname - network address of your MongoDB deployment, accessible by your client

  • port - port number of your MongoDB deployment

  • authenticationDb - MongoDB database that contains your user's authentication data. If you omit this parameter, the driver uses the default value admin.

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. Your code to instantiate a MongoClient should look something like this:

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. Your code to instantiate a MongoClient should look something like this:

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 on the challenge-response (CR) and salted challenge-response authentication mechanisms (SCRAM) that MongoDB supports, see the SCRAM section of the MongoDB Server manual.

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 username.

  • password - your MongoDB user's password.

  • hostname - network address of your MongoDB deployment, accessible by your client.

  • port - port number of your MongoDB deployment.

  • authenticationDb - MongoDB database that contains your user's authentication data. If you omit this parameter, the driver uses the default value admin.

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. Your code to instantiate a MongoClient should look something like this:

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. Your code to instantiate a MongoClient should look something like this:

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());

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 username.

  • password - your MongoDB user's password.

  • hostname - network address of your MongoDB deployment, accessible by your client.

  • port - port number of your MongoDB deployment.

  • authenticationDb - MongoDB database that contains your user's authentication data. If you omit this parameter, the driver uses the default value admin.

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. Your code to instantiate a MongoClient should look something like this:

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. Your code to instantiate a MongoClient should look something like this:

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 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.

Note

The MONGODB-AWS authentication mechanism is available in MongoDB Atlas.

The MONGODB-AWS authentication mechanism uses your Amazon Web Services Identity and Access Management (AWS IAM) credentials to authenticate your user.

You can store your AWS credentials as environment variables, or insert them inline like the examples below. The driver checks for your credentials in the following order:

  1. Supplied values in a MongoCredential object or the provided connection string.

  2. Your environment variables. (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and optionally AWS_SESSION_TOKEN)

  3. The AWS EC2 endpoint specified in the AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment variable.

  4. The default AWS EC2 endpoint. For more information, see IAM Roles for Tasks

The following code snippets show how to specify the authentication mechanism, using the following placeholders:

  • awsKeyId - value of your AWS_ACCESS_KEY_ID.

  • awsSecretKey - value of your AWS_SECRET_ACCESS_KEY.

  • atlasUri - network address of your MongoDB Atlas instance.

  • awsSessionToken - value of your AWS_SESSION_TOKEN. (optional)

Important

URL-encode Your Credentials

Make sure to URL-encode your credentials to prevent backslash or other characters from causing parsing errors. The following code example shows you how to URL-encode a sample string, represented by the placeholder fieldValue:

String encodedField = java.net.URLEncoder.encode("<fieldValue>".toString(), "ISO-8859-1");

Select the Connection String or the MongoCredential tab below for instructions and sample code for specifying this authentication mechanism:

To specify the MONGODB-AWS authentication mechanism using a connection string, assign the authMechanism parameter the value "MONGODB-AWS" in your connection string. Your code to instantiate a MongoClient should look something like this:

MongoClient mongoClient = MongoClients.create("mongodb://<awsKeyId>:<awsSecretKey>@<atlasUri>?authMechanism=MONGODB-AWS");

If you need to specify an AWS session token, include it in the authMechanismProperties parameter as follows using the format AWS_SESSION_TOKEN:<awsSessionToken>. Your code to instantiate a MongoClient with a session token should look something like this:

MongoClient mongoClient = MongoClients.create("mongodb://<awsKeyId>:<awsSecretKey>@<atlasUri>?authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:<awsSessionToken>");

To specify the MONGODB-AWS authentication mechanism using the MongoCredential class, use the createAwsCredential() method. Your code to instantiate a MongoClient should look something like this:

MongoCredential credential = MongoCredential.createAwsCredential("<awsKeyId>", "<awsSecretKey>".toCharArray());
MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder()
.applyToClusterSettings(builder ->
builder.hosts(Arrays.asList(new ServerAddress("<hostname>"))))
.credential(credential)
.build());

If you need to specify an AWS session token, you can add it using one of the following choices:

  • Specify your AWS session token in a connection string.

    If you prefer to pass the AWS session token in the connection string alongside your MongoCredential, specify your authentication mechanism in the authMechanism parameter and your session token in the authMechanismProperties parameter. Then, add it to your MongoClientSettings by calling the applyConnectionString() method as follows:

    MongoCredential credential = MongoCredential.createAwsCredential("<awsKeyId>", "<awsSecretKey>".toCharArray());
    ConnectionString connectionString = new ConnectionString("mongodb://<atlasUri>/?authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:<awsSessionToken>");
    MongoClient mongoClient = MongoClients.create(
    MongoClientSettings.builder()
    .applyConnectionString(connectionString)
    .credential(credential)
    .build());
  • Specify your AWS session token in a MongoCredential.

    You can include your AWS session token in your MongoCredential instance by specifying it in a call to the withMechanismProperty() method as shown below:

    MongoCredential credential = MongoCredential.createAwsCredential("<awsKeyId>", "<awsSecretKey>".toCharArray()).withMechanismProperty("AWS_SESSION_TOKEN", "<awsSessionToken>");
    ConnectionString connectionString = new ConnectionString("mongodb://<atlasUri>/?authMechanism=MONGODB-AWS");
    MongoClient mongoClient = MongoClients.create(
    MongoClientSettings.builder()
    .applyConnectionString(connectionString)
    .credential(credential)
    .build());
  • Specify your AWS session token in an environment variable.

    In your client execution environment, set an environment variable called AWS_SESSION_TOKEN and assign your token to it. The value is automatically picked up by your MongoClient when you specify the MONGODB-AWS authentication mechanism.

The driver supports refreshing credentials for cases such as assuming roles or using Elastic Kubernetes Service.

Supplier<AwsCredential> awsFreshCredentialSupplier = () -> {
// Add your code to fetch new credentials, such as assuming a role using the AWS SDK.
// Ensure you return the temporary credentials.
return new AwsCredential("<awsKeyId>", "<awsSecretKey>", "<awsSessionToken>");
};
MongoCredential credential = MongoCredential.createAwsCredential(null, null)
.withMechanismProperty(MongoCredential.AWS_CREDENTIAL_PROVIDER_KEY, awsFreshCredentialSupplier);
MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder()
.applyToClusterSettings(builder ->
builder.hosts(Collections.singletonList(new ServerAddress("<hostname>", 27017))))
.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.

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, accessible by your client.

  • port - port number of your MongoDB deployment.

  • authenticationDb - MongoDB database that contains your user's authentication data. If you omit this parameter, the driver uses the default value admin.

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. Your code to instantiate a MongoClient should look something like this:

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. Your code to instantiate a MongoClient should look something like this:

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());

For additional information on configuring your application to use certificates as well as TLS/SSL options, see our TLS/SSL guide.

Back

Connect to MongoDB Using a JNDI Datasource