Docs Menu
Docs Home
/ / /
Kotlin Sync Driver
/

Authentication Mechanisms

On this page

  • Overview
  • Default
  • SCRAM-SHA-256
  • SCRAM-SHA-1
  • MONGODB-X509
  • MONGODB-AWS
  • AWS SDK
  • Specify Your Credentials in the Environment
  • Specify Your Credentials in a MongoCredential
  • Additional Information

In this guide, you can learn how to authenticate to a MongoDB Server by using each authentication mechanism available in the MongoDB Kotlin Sync Driver. Authentication is the process by which the driver proves its identity to the server to ensure security.

Note

Enterprise Authentication Mechanisms

This page describes the authentication mechanisms available in MongoDB Community Edition. To authenticate with mechanisms available in the MongoDB Enterprise Edition, like Kerberos or LDAP, see the Enterprise Authentication Mechanisms guide.

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

  1. SCRAM-SHA-256: An authentication mechanism that uses your database username and password, encrypted with the SHA-256 algorithm

  2. SCRAM-SHA-1: An authentication mechanism that uses your database username and password, encrypted with the SHA-1 algorithm

MongoDB Server versions 4.0 and later use SCRAM-SHA-256 as the default authentication mechanism.

The following code snippets show how to use the default authentication mechanism by using the following placeholders:

  • db_username: Your MongoDB database username.

  • db_password: Your MongoDB database user's password.

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

  • port: The port number of your MongoDB deployment.

  • authenticationDb: The 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 by using a connection string, omit the mechanism. Your code to instantiate a MongoClient should resemble the following:

val mongoClient =
MongoClient.create("mongodb://<db_username>:<db_password>@<hostname>:<port>/?authSource=<authenticationDb>")

To specify the default authentication mechanism by using the MongoCredential class, use the createCredential() method. Your code to instantiate a MongoClient should resemble the following:

val credential = MongoCredential.createCredential(
"<db_username>", "<authenticationDb>", "<db_password>".toCharArray()
)
val settings = MongoClientSettings.builder()
.applyToClusterSettings { builder: ClusterSettings.Builder ->
builder.hosts(
listOf(ServerAddress("<hostname>", <port>))
)
}
.credential(credential)
.build()
val mongoClient = MongoClient.create(settings)

For more information about using SCRAM with MongoDB, see the SCRAM section of the MongoDB Server manual.

Note

SCRAM-SHA-256 is the default authentication method for MongoDB Server versions 4.0 and later.

SCRAM-SHA-256, as defined by RFC 7677, 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 by using the following placeholders:

  • db_username: Your MongoDB database username.

  • db_password: Your MongoDB database user's password.

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

  • port: The port number of your MongoDB deployment.

  • authenticationDb: The 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 by using a connection string, assign the authMechanism parameter the value SCRAM-SHA-256 in your connection string. Your code to instantiate a MongoClient should resemble the following:

val mongoClient =
MongoClient.create("mongodb://<db_username>:<db_password>@<hostname>:<port>/?authSource=admin&authMechanism=SCRAM-SHA-256")

To specify the default authentication mechanism by using the MongoCredential class, use the createScramSha256Credential() method. Your code to instantiate a MongoClient should resemble the following:

val credential = MongoCredential.createScramSha256Credential(
"<db_username>", "<authenticationDb>", "<db_password>".toCharArray()
)
val settings = MongoClientSettings.builder()
.applyToClusterSettings { builder: ClusterSettings.Builder ->
builder.hosts(
listOf(ServerAddress("<hostname>", <port>))
)
}
.credential(credential)
.build()
val mongoClient = MongoClient.create(settings)

Note

SCRAM-SHA-1 is the default authentication method for MongoDB versions MongoDB Server versions 3.6 and earlier.

SCRAM-SHA-1, as defined by RFC 5802, is a Salted Challenge Response Authentication 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 by using the following placeholders:

  • db_username: Your MongoDB database username.

  • db_password: Your MongoDB database user's password.

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

  • port: The port number of your MongoDB deployment.

  • authenticationDb: The 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 by using a connection string, assign the authMechanism parameter the value SCRAM-SHA-1 in your connection string. Your code to instantiate a MongoClient should resemble the following:

val mongoClient =
MongoClient.create("mongodb://<db_username>:<db_password>@<hostname>:<port>/?authSource=admin&authMechanism=SCRAM-SHA-1")

To specify the default authentication mechanism by using the MongoCredential class, use the createScramSha1Credential() method. Your code to instantiate a MongoClient should resemble the following:

val credential = MongoCredential.createScramSha1Credential(
"<db_username>", "<authenticationDb>", "<db_password>".toCharArray()
)
val settings = MongoClientSettings.builder()
.applyToClusterSettings { builder: ClusterSettings.Builder ->
builder.hosts(
listOf(ServerAddress("<hostname>", <port>))
)
}
.credential(credential)
.build()
val mongoClient = MongoClient.create(settings)

The MONGODB-X509 authentication mechanism uses TLS with X.509 certificates to authenticate your user. When you specify the X.509 authentication mechanism, the server authenticates the connection by using the subject name of the client certificate.

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

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

  • port: The port number of your MongoDB server.

  • authenticationDb: The 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 by 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 resemble the following:

val mongoClient =
MongoClient.create("mongodb://<db_username>:<db_password>@<hostname>:<port>/?authSource=<authenticationDb>&authMechanism=MONGODB-X509&tls=true")

To specify the X.509 authentication mechanism by 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 resemble the following:

val credential = MongoCredential.createMongoX509Credential()
val settings = MongoClientSettings.builder()
.applyToClusterSettings { builder ->
builder.hosts(listOf(
ServerAddress("<hostname>", <port>))
)
}
.applyToSslSettings { builder ->
builder.enabled(true)
}
.credential(credential)
.build()
val mongoClient = MongoClient.create(settings)

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

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 Authentication with AWS IAM guide.

To instruct the driver to use this authentication mechanism, you can either specify MONGODB-AWS as a parameter in the connection string or call the MongoCredential.createAwsCredential() factory method.

In the following sections, you can learn different ways to specify the MONGODB-AWS authentication mechanism and provide your AWS IAM credentials.

These sections contain code examples that use the following placeholders:

  • awsKeyId: The value of your AWS access key ID

  • awsSecretKey: The value of your AWS secret access key

  • atlasUri: The network address of your MongoDB Atlas deployment

  • hostname: The hostname of your MongoDB Atlas deployment

  • port: The port of your MongoDB Atlas deployment

  • awsSessionToken: The value of your AWS session token

Note

End of Support for AWS SDK for Java v1

The AWS SDK for Java v1 will reach end of support on December 31, 2025. AWS recommends migrating to AWS SDK for Java v2. For more information, see the end of support announcement on the AWS site.

AWS provides software development kits (SDKs) for Java v1 and v2. The AWS SDK 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 MONGODB-AWS authentication, you must perform the following steps:

  1. Specify the authentication mechanism.

  2. Add the SDK as a dependency to your project.

  3. Supply your credentials by using one of the methods in the credential provider chain.

To specify the MONGODB-AWS authentication mechanism by using a MongoCredential object, call the MongoCredential.createAwsCredential() factory method and add the MongoCredential instance to your MongoClient, as shown in the following example:

val credential = MongoCredential.createAwsCredential(null, null)
val settings = MongoClientSettings.builder()
.applyToClusterSettings { builder: ClusterSettings.Builder ->
builder.hosts(
listOf(ServerAddress("<atlasUri>"))
)
}
.credential(credential)
.build()
val mongoClient = MongoClient.create(settings)

To specify the MONGODB-AWS authentication mechanism in the connection string, add it as a parameter, as shown in the following example:

val mongoClient =
MongoClient.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:

Note

For the AWS SDK for Java v2, the Java driver currently tests by using the software.amazon.awssdk:auth:2.18.9 dependency.

For the AWS SDK for Java v1, the Java driver currently tests by 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:

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.

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:

  1. Specify the authentication mechanism.

  2. Add the appropriate environment variables.

You can specify the MONGODB-AWS authentication mechanism by using a MongoCredential object or in the connection string.

To specify the authentication mechanism by using a MongoCredential object, call the MongoCredential.createAwsCredential() factory method and add the MongoCredential instance to your MongoClient, as shown in the following example:

val credential = MongoCredential.createAwsCredential(null, null)
val settings = MongoClientSettings.builder()
.applyToClusterSettings { builder: ClusterSettings.Builder ->
builder.hosts(
listOf(ServerAddress("<atlasUri>"))
)
}
.credential(credential)
.build()
val mongoClient = MongoClient.create(settings)

To specify the MONGODB-AWS authentication mechanism in the connection string, add it as a parameter as shown in the following example:

val mongoClient =
MongoClient.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

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

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 aforementioned environment variables are set. The driver obtains the credentials from the default IPv4 EC2 instance metadata endpoint.

You can supply your AWS IAM credentials to a MongoClient by using a MongoCredential instance. To construct the MongoCredential instance for MONGODB-AWS authentication, call the createAwsCredential() factory method.

You can supply only programmatic access keys to the MongoCredential.createAwsCredential() method. If you need to supply ECS or EC2 container credentials, follow the instructions in Specify Your Credentials in the Environment or AWS SDK.

To use a MongoCredential object for MONGODB-AWS authentication, you must perform the following steps:

  1. Specify the authentication mechanism.

  2. Supply the credentials.

To specify the authentication mechanism by using a MongoCredential object, call the MongoCredential.createAwsCredential() factory method and add the MongoCredential instance to your MongoClient, as shown in the following example:

val credential = MongoCredential.createAwsCredential("<awsKeyId>", "<awsSecretKey>".toCharArray())
val settings = MongoClientSettings.builder()
.applyToClusterSettings { builder: ClusterSettings.Builder ->
builder.hosts(
listOf(ServerAddress("<atlasUri>"))
)
}
.credential(credential)
.build()
val mongoClient = MongoClient.create(settings)

If you need to specify an AWS session token, pass it to the withMechanismProperty() method, as shown in the following example:

val credential = MongoCredential.createAwsCredential("<awsKeyId>", "<awsSecretKey>".toCharArray())
.withMechanismProperty("AWS_SESSION_TOKEN", "<awsSessionToken>")
val settings = MongoClientSettings.builder()
.applyToClusterSettings { builder: ClusterSettings.Builder ->
builder.hosts(
listOf(ServerAddress("<atlasUri>"))
)
}
.credential(credential)
.build()
val mongoClient = MongoClient.create(settings)

To refresh your credentials, you can declare a Supplier lambda expression that returns new credentials, as shown in the following example:

val awsFreshCredentialSupplier: Supplier<AwsCredential> = Supplier {
// Add your code here to fetch new credentials
// Return the new credentials
AwsCredential("<awsKeyId>", "<awsSecretKey>", "<awsSessionToken>")
}
val credential = MongoCredential.createAwsCredential("<awsKeyId>", "<awsSecretKey>".toCharArray())
.withMechanismProperty(MongoCredential.AWS_CREDENTIAL_PROVIDER_KEY, awsFreshCredentialSupplier)
val settings = MongoClientSettings.builder()
.applyToClusterSettings { builder ->
builder.hosts(listOf(ServerAddress("<hostname>", <port>)))
}
.credential(credential)
.build()
val mongoClient = MongoClient.create(settings)

If you must provide AWS IAM credentials in a connection string, you can add it to your MongoClientSettings object by calling the applyConnectionString() method:

val credential = MongoCredential.createAwsCredential("<awsKeyId>", "<awsSecretKey>".toCharArray())
val connectionString = ConnectionString("mongodb://<atlasUri>/?authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:<awsSessionToken>")
val settings = MongoClientSettings.builder()
.applyConnectionString(connectionString)
.credential(credential)
.build()
val mongoClient = MongoClient.create(settings)

To learn more about authenticating to MongoDB, see Authentication in the MongoDB Server manual.

To learn more about managing users of your MongoDB deployment, see Users in the MongoDB Server manual.

Back

Security