Enterprise Authentication Mechanisms
In this guide, you can find sample code for connection to MongoDB with each
authentication mechanism available in the MongoDB Enterprise Edition:
Kerberos (GSSAPI/SSPI)
, LDAP (PLAIN)
, and MONGODB-OIDC
.
Kerberos (GSSAPI/SSPI)
Note
The Node.js driver supports Kerberos on UNIX using the MIT Kerberos library and on Windows using the SSPI API.
The GSSAPI
authentication mechanism uses your user principal to
authenticate to a Kerberos service.
You can specify this authentication mechanism by performing the following actions while specifying options on your connection string:
Set the
authMechanism
parameter toGSSAPI
.Set the
SERVICE_NAME
value in theauthMechanismProperties
parameter if using a value other thanmongodb
.Specify a
SERVICE_REALM
value in theauthMechanismProperties
parameter if a custom service realm is required.Specify a
CANONICALIZE_HOST_NAME
value in theauthMechanismProperties
parameter if canonicalization of the hostname is required. This property can take the following values:none
: (Default) Does not perform hostname canonicalizationforward
: Performs a forward DNS lookup to canonicalize the hostnameforwardAndReverse
: Performs a forward DNS lookup and then a reverse lookup on that value to canonicalize the hostname
Important
The gssapiServiceName
parameter is deprecated and may be removed
in future versions of the driver. Use
authMechanismProperties=SERVICE_NAME:<your service name>
in the
connection URI instead.
See the
authMechanismProperties
parameter documentation for more information.
The following code sample authenticates to Kerberos for UNIX using GSSAPI
.
Important
Always URI encode the principal using the encodeURIComponent
method
to ensure it is correctly parsed.
const { MongoClient } = require("mongodb"); // specify the placeholder values for your environment in the following lines const clusterUrl = "<MongoDB cluster URL>"; const principal = encodeURIComponent("<Kerberos principal and realm>"); const serviceRealm = "<Kerberos service realm>"; const canonicalizationSetting = "<canonicalization setting>"; const authMechanismProperties = `SERVICE_REALM:${serviceRealm},CANONICALIZE_HOST_NAME:${canonicalizationSetting}`; const authMechanism = "GSSAPI"; // Connection URI const uri = `mongodb+srv://${principal}@${clusterUrl}/?authMechanism=${authMechanism}&authMechanismProperties=${authMechanismProperties}`; const client = new MongoClient(uri); // Function to connect to the server async function run() { try { // Establish and verify connection await client.db("admin").command({ ping: 1 }); console.log("Connected successfully to server"); } finally { // Ensures that the client will close when you finish/error await client.close(); } } run().catch(console.dir);
Note
The method refers to the GSSAPI
authentication mechanism instead
of Kerberos
because the driver authenticates through
GSSAPI RFC-4652, the SASL
mechanism.
LDAP (PLAIN)
The PLAIN
authentication mechanism uses your username and password to
authenticate to a Lightweight Directory Access Protocol (LDAP) server.
You can specify this authentication mechanism by setting the authMechanism
parameter to PLAIN
and including your LDAP username and password in the
connection string as shown
in the following sample code.
const { MongoClient } = require("mongodb"); // specify the placeholder values for your environment in the following lines const clusterUrl = "<MongoDB cluster URL>"; const ldapUsername = "<LDAP username>"; const ldapPassword = "<LDAP password>"; const authMechanism = "PLAIN"; // Connection URI const uri = `mongodb+srv://${ldapUsername}:${ldapPassword}@${clusterUrl}/?authMechanism=${authMechanism}`; const client = new MongoClient(uri); // Function to connect to the server async function run() { try { // Establish and verify connection await client.db("admin").command({ ping: 1 }); console.log("Connected successfully to server"); } finally { // Ensures that the client will close when you finish/error await client.close(); } } run().catch(console.dir);
Note
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.
MONGODB-OIDC
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 from various platforms.
For more information about the MONGODB-OIDC authentication mechanism, see OpenID Connect Authentication and MongoDB Server Parameters in the MongoDB Server manual.
Azure IMDS
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 Node.js driver's built-in Azure support.
To specify Azure IMDS OIDC as the authentication mechanism, set the following options in your connection string:
username
: If you're using an Azure managed identity, set this to the client ID of the managed identity. If you're using a service principal to represent an enterprise application, set this to the application ID of the service principal. Otherwise, omit this option.authMechanism
: Set toMONGODB-OIDC
.authMechanismProperties
: Set toENVIRONMENT:azure,TOKEN_RESOURCE:<audience>
. Replace the<audience>
placeholder with the value of theaudience
parameter configured on your MongoDB deployment.
The following code example shows how to set the preceding connection options:
const { MongoClient } = require("mongodb"); const uri = "mongodb+srv://<username>@<hostname>:<port>/?authMechanism=MONGODB-OIDC" + "&authMechanismProperties=ENVIRONMENT:azure,TOKEN_RESOURCE:<audience>"; const client = new MongoClient(uri);
GCP IMDS
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 Node.js driver's built-in GCP support.
To specify GCP IMDS OIDC as the authentication mechanism, set the following options in your connection string:
authMechanism
: Set toMONGODB-OIDC
.authMechanismProperties
: Set toENVIRONMENT:gcp,TOKEN_RESOURCE:<audience>
. Replace the<audience>
placeholder with the value of theaudience
parameter configured on your MongoDB deployment.
The following code example shows how to set the preceding connection options:
const { MongoClient } = require("mongodb"); const uri = "mongodb+srv://<host>:<port>/?authMechanism=MONGODB-OIDC" + "&authMechanismProperties=ENVIRONMENT:gcp,TOKEN_RESOURCE:<audience>"; const client = new MongoClient(uri);
Custom Callback
The Node.js 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.
First, define a function that retrieves the access token to use for OIDC authentication. This function must have the following signature:
const myCallback = (params: OIDCCallbackParams): Promise<OIDCResponse> => { }
The OIDCCallbackParams
parameter contains the following properties, which you can
access inside the function:
Property | Value |
---|---|
timeoutContext | An AbortSignal that aborts the authentication workflow after 30 seconds |
version | The current OIDC API version |
idpInfo | The identity-provider information returned from the server |
username | The username included in the connection string, if any |
refreshToken | The refresh token to request a new access token from the issuer, if any |
The callback function must return an OIDCResponse
object. This object contains the
following properties:
Property | Value |
---|---|
accessToken | The access token to use for authentication. |
expiresInSeconds | Optional. The number of seconds until the access token expires. |
refreshToken | Optional. The refresh token to request a new access token from the issuer. |
The following example shows a callback function that retrieves an OIDC access token
from a file named access-token.dat
in the local file system:
const fs = require("node:fs"); const myCallback = (params: OIDCCallbackParams): Promise<OIDCResponse> => { const token = fs.readFileSync("access-token.dat", "utf8"); return { accessToken: token, expiresInSeconds: 300, refreshToken: token }; }
After you define your callback function, pass it to the MongoClient
constructor
as part of the authMechanismProperties
parameter. The Node.js driver supports
the following authentication patterns:
Machine authentication: Used by web services and other applications that require no human interaction. Select the Machine Callback tab to see an example of this syntax.
Human authentication: Used by database tools, command-line utilities, and other applications that involve direct human interaction. Select the Human Callback tab to see an example of this syntax.
For machine authentication, assign the callback function to the
authMechanismProperties.OIDC_CALLBACK
property, as shown in the following
example:
const { MongoClient } = require("mongodb"); const uri = "mongodb+srv://<host>:<port>/?authMechanism=MONGODB-OIDC"; const client = new MongoClient(uri, { authMechanismProperties: { OIDC_CALLBACK: myCallback } });
For human authentication, assign the callback function to the
authMechanismProperties.OIDC_HUMAN_CALLBACK
property, as shown in the following
example:
const { MongoClient } = require("mongodb"); const uri = "mongodb+srv://<host>:<port>/?authMechanism=MONGODB-OIDC"; const client = new MongoClient(uri, { authMechanismProperties: { OIDC_HUMAN_CALLBACK: myCallback } });
API Documentation
To learn more about the methods and types discussed in this guide, see the following API documentation: