Docs Menu
Docs Home
/ / /
Kotlin Coroutine
/

Enterprise Authentication Mechanisms

On this page

  • Overview
  • Specify an Authentication Mechanism
  • Mechanisms
  • Kerberos (GSSAPI)
  • LDAP (PLAIN)
  • MONGODB-OIDC

In this guide, you can learn how to authenticate with MongoDB using each authentication mechanism available exclusively in the MongoDB Enterprise Edition.

You can use the following mechanisms with the latest version of MongoDB Enterprise Edition:

  • Kerberos (GSSAPI)

  • LDAP (PLAIN)

  • MONGODB-OIDC

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 MongoClient.create() method to instantiate your MongoClient. The Connection String tab in each section provides 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. The MongoCredential tab in each section provides the syntax for authenticating using a MongoCredential.

For more information on these classes and methods, refer to the following API documentation:

The Generic Security Services API (GSSAPI) authentication mechanism allows the user to authenticate to a Kerberos service using the user's principal name.

Note

The method refers to the GSSAPI authentication mechanism instead of Kerberos because the driver authenticates using the GSSAPI RFC-4652 SASL mechanism.

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

  • Kerberos principal - your URL-encoded principal name, e.g. "username%40REALM.ME"

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

  • port - port number of your MongoDB server

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

To specify the GSSAPI authentication mechanism using a connection string:

  • Assign the authMechanism URL parameter to the value GSSAPI

  • (optional) Assign the authSource URL parameter to the value $external

Note

If you specify the GSSAPI mechanism, you cannot assign authSource to any value other than $external.

Your code to instantiate a MongoClient should resemble the following:

val connectionString = ConnectionString("<Kerberos principal>@<hostname>:<port>/?authSource=$external&authMechanism=GSSAPI")
val mongoClient = MongoClient.create(connectionString)

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

val credential = MongoCredential.createGSSAPICredential("<Kerberos principal>")
val settings = MongoClientSettings.builder()
.applyToClusterSettings { builder ->
builder.hosts(listOf(ServerAddress("<hostname>", <port>)))
}
.credential(credential)
.build()
val mongoClient = MongoClient.create(settings)

In order to acquire a Kerberos ticket, the GSSAPI Java libraries require you to specify the realm and Key Distribution Center (KDC) system properties. See the sample settings in the following example:

java.security.krb5.realm=MYREALM.ME
java.security.krb5.kdc=mykdc.myrealm.me

You may need to specify one or more of the following additional MongoCredential mechanism properties depending on your Kerberos setup:

  • SERVICE_NAME

  • CANONICALIZE_HOST_NAME

  • JAVA_SUBJECT

  • JAVA_SASL_CLIENT_PROPERTIES

  • JAVA_SUBJECT_PROVIDER

Important

You can only specify the following GSSAPI properties using the MongoCredential:

  • JAVA_SUBJECT

  • JAVA_SASL_CLIENT_PROPERTIES

  • JAVA_SUBJECT_PROVIDER

Select the MongoCredential tab to see how to specify them.

To specify one of the GSSAPI additional properties, include it in the connection string as a URL parameter using the format: <PROPERTY_NAME>:<value>.

Your code to instantiate a MongoClient using GSSAPI and additional properties might resemble the following:

val connectionString = ConnectionString("<Kerberos principal>@<hostname>:<port>/?authSource=$external&authMechanism=GSSAPI&authMechanismProperties=SERVICE_NAME:myService")
val mongoClient = MongoClient.create(connectionString)

To specify one of the GSSAPI additional properties, call the withMechanismProperty() method on your MongoCredential instance and pass the property name and value as parameters. Use the property name constants defined in the MongoCredential class:

Select the SERVICE_NAME_KEY or JAVA_SUBJECT_KEY tab to see sample code to instantiate a MongoCredential that uses GSSAPI and the selected property:

val credential = MongoCredential.createGSSAPICredential("<Kerberos principal>")
.withMechanismProperty(MongoCredential.SERVICE_NAME_KEY, "myService")
val loginContext = LoginContext("<LoginModule implementation from JAAS config>")
loginContext.login()
val subject: Subject = loginContext.subject
val credential = MongoCredential.createGSSAPICredential("<Kerberos principal>")
.withMechanismProperty(MongoCredential.JAVA_SUBJECT_KEY, subject)

By default, the Kotlin driver caches Kerberos tickets by MongoClient instance. If your deployment needs to frequently create and destroy MongoClient instances, you can change the default Kerberos ticket caching behavior to cache by process to improve performance.

To cache Kerberos tickets by process, you must use the MongoCredential authentication mechanism, as the connection string authentication mechanism does not support the JAVA_SUBJECT_PROVIDER mechanism property. If you would like to cache Kerberos tickets by process, select the MongoCredential tab to learn how to accomplish this.

To cache Kerberos tickets by process, you must specify the JAVA_SUBJECT_PROVIDER mechanism property and provide a KerberosSubjectProvider in your MongoCredential instance. The code to configure the Kotlin driver to cache Kerberos tickets by process should resemble the following:

/* All MongoClient instances sharing this instance of KerberosSubjectProvider
will share a Kerberos ticket cache */
val myLoginContext = "myContext"
/* Login context defaults to "com.sun.security.jgss.krb5.initiate"
if unspecified in KerberosSubjectProvider */
val credential = MongoCredential.createGSSAPICredential("<Kerberos principal>")
.withMechanismProperty(
MongoCredential.JAVA_SUBJECT_PROVIDER_KEY,
KerberosSubjectProvider(myLoginContext)
)

Note

On Windows, Oracle’s JRE uses LSA rather than SSPI in its implementation of GSSAPI which limits interoperability with Windows Active Directory and implementations of single sign-on. See the following articles for more information:

Available in MongoDB Enterprise Edition 3.4 and later.

You can authenticate to a Lightweight Directory Access Protocol (LDAP) server using your directory server username and password.

Tip

The authentication mechanism is named PLAIN instead of LDAP since it authenticates using the PLAIN Simple Authentication and Security Layer (SASL) defined in RFC-4616.

You can specify this authentication mechanism by setting the authMechanism parameter to PLAIN and including your LDAP username and password in the connection string.

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

  • LDAP username - your LDAP username

  • password - your LDAP user's password

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

  • port - port number of your MongoDB server

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

To specify the LDAP (PLAIN) authentication mechanism using a connection string:

  • Assign the authMechanism URL parameter to the value PLAIN

  • (optional) Assign the authSource URL parameter to the value $external

Note

If you specify the PLAIN mechanism, you cannot assign authSource to any value other than $external.

Your code to instantiate a MongoClient should resemble the following:

val connectionString = ConnectionString("<LDAP username>:<password>@<hostname>:<port>/?authSource=$external&authMechanism=PLAIN")
val mongoClient = MongoClient.create(connectionString)

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

val credential = MongoCredential.createPlainCredential("<LDAP username>", "$external", "<password>".toCharArray())
val settings = MongoClientSettings.builder()
.applyToClusterSettings { builder ->
builder.hosts(listOf(ServerAddress("<hostname>", <port>)))
}
.credential(credential)
.build()
val mongoClient = MongoClient.create(settings)

Important

The MONGODB-OIDC authentication mechanism requires MongoDB server v7.0 or later running on a Linux platform.

The following sections describe how to use the MONGODB-OIDC authentication mechanism to authenticate to various platforms.

For more information about the MONGODB-OIDC authentication mechanism, see OpenID Connect Authentication and MongoDB Server Parameters in the MongoDB Server manual.

If your application runs on an Azure VM, or otherwise uses the Azure Instance Metadata Service (IMDS), you can authenticate to MongoDB by using the Kotlin driver's built-in Azure support.

You can specify Azure IMDS OIDC authentication either by using a MongoCredential instance or by specifying your credentials in the connection string.

Select from the Connection String or MongoCredential tabs to see the corresponding syntax.

Replace the <percent-encoded audience> placeholder in the following code with the percent-encoded value of the audience server parameter configured on your MongoDB deployment.

The comma (,) character and its encoding (%2C) are reserved, and using these characters in a value causes the driver to interpret commas as delimiters of key-value pairs. You must specify values that contain commas in a MongoCredential instance, as demonstrated in the MongoCredential tab.

val connectionString = ConnectionString(
"mongodb://<OIDC principal>@<hostname>:<port>/?" +
"?authMechanism=MONGODB-OIDC" +
"&authMechanismProperties=ENVIRONMENT:azure,TOKEN_RESOURCE:<percent-encoded audience>")
val mongoClient = MongoClient.create(connectionString)

Replace the <OIDC principal> placeholder with the client ID or application ID of the Azure managed identity or enterprise application. Replace the <audience> placeholder with the value of the audience server parameter configured on your MongoDB deployment.

val credential = MongoCredential.createOidcCredential("<OIDC principal>")
.withMechanismProperty("ENVIRONMENT", "azure")
.withMechanismProperty("TOKEN_RESOURCE", "<audience>")
val mongoClient = MongoClient.create(
MongoClientSettings.builder()
.applyToClusterSettings { builder ->
builder.hosts(listOf(ServerAddress("<hostname>", <port>)))
}
.credential(credential)
.build())

If your application runs on a Google Compute Engine VM, or otherwise uses the GCP Instance Metadata Service, you can authenticate to MongoDB by using the Kotlin driver's built-in GCP support.

You can specify GCP IMDS OIDC authentication either by using a MongoCredential instance or by specifying your credentials in the connection string.

Select from the Connection String or MongoCredential tabs to see the corresponding syntax.

Replace the <percent-encoded audience> placeholder in the following code with the percent-encoded value of the audience server parameter configured on your MongoDB deployment.

The comma (,) character and its encoding (%2C) are reserved, and using these characters in a value causes the driver to interpret commas as delimiters of key-value pairs. You must specify values that contain commas in a MongoCredential instance, as demonstrated in the MongoCredential tab.

val connectionString = ConnectionString(
"mongodb://<OIDC principal>@<hostname>:<port>/?" +
"authMechanism=MONGODB-OIDC" +
"&authMechanismProperties=ENVIRONMENT:gcp,TOKEN_RESOURCE:<percent-encoded audience>")
val mongoClient = MongoClient.create(connectionString)

Replace the <audience> placeholder with the value of the audience server parameter configured on your MongoDB deployment.

val credential = MongoCredential.createOidcCredential("<OIDC principal>")
.withMechanismProperty("ENVIRONMENT", "gcp")
.withMechanismProperty("TOKEN_RESOURCE", "<audience>")
val mongoClient = MongoClient.create(
MongoClientSettings.builder()
.applyToClusterSettings { builder ->
builder.hosts(listOf(ServerAddress("<hostname>", <port>)))
}
.credential(credential)
.build())

The Kotlin driver doesn't offer built-in support for all platforms, including Azure Functions and Azure Kubernetes Service (AKS). Instead, you must define a custom callback to use OIDC to authenticate from these platforms. To do so, use the "OIDC_CALLBACK" authentication property, as shown in the following code example:

val credential = MongoCredential.createOidcCredential(null)
.withMechanismProperty("OIDC_CALLBACK") { context: Context ->
val accessToken = "..."
OidcCallbackResult(accessToken)
}

The value of the "OIDC_CALLBACK" property must be a lambda or other implementation of the OidcCallback functional interface that accepts an OidcCallbackContext as a parameter and returns an OidcCallbackResult.

The following example uses an example callback to retrieve an OIDC token from a file named "access-token.dat" in the local file system:

val credential = MongoCredential.createOidcCredential(null)
.withMechanismProperty("OIDC_CALLBACK") { context: Context ->
val accessToken = String(Files.readAllBytes(Paths.get("access-token.dat")))
OidcCallbackResult(accessToken)
}
val mongoClient = MongoClient.create(
MongoClientSettings.builder()
.applyToClusterSettings { builder ->
builder.hosts(listOf(ServerAddress("<hostname>", <port>)))
}
.credential(credential)
.build()
)

Back

Authentication