Authentication Mechanisms
On this page
Overview
In this guide, you can learn how to authenticate with MongoDB using the authentication mechanisms available in the MongoDB Community Edition. Authentication mechanisms are processes by which the driver and server confirm the identity of a client to ensure security before connecting.
You can use the following authentication mechanisms with the latest version of MongoDB Community Edition:
To authenticate using GSSAPI/Kerberos
or LDAP
, see the
Enterprise Authentication Mechanisms fundamentals page. For more
information on establishing a connection to your MongoDB cluster, see the
Connection Guide.
Specify an Authentication Mechanism
You can specify your authentication mechanism and credentials when connecting to MongoDB using either of the following methods:
A connection string, also known as a connection URI, which is a string that tells the driver how to connect to a MongoDB deployment and how to behave while connected.
A factory method for the supported authentication mechanism, contained in the
MongoCredential
class.
Mechanisms
The following examples contain code examples that use the following placeholders:
<db_username>
- MongoDB username.<db_password>
- MongoDB user's password.<hostname>
- network address of the MongoDB server, accessible by your client.<port>
- port number of the MongoDB server.<authenticationDb>
- MongoDB database that contains the user's authentication data. If you omit this parameter, the driver uses the default valueadmin
.
Default
The default authentication mechanism setting uses one of the following authentication mechanisms, depending on which MongoDB versions your server supports:
SCRAM-SHA-256
SCRAM-SHA-1
Select the Connection String or MongoCredential tab to see the corresponding syntax for specifying the default authentication mechanism:
var mongoClient = new MongoClient("mongodb://<db_username>:<db_password>@<hostname>:<port>/?authSource=<authenticationDb>");
var credential = MongoCredential.CreateCredential("<authenticationDb>", "<db_username>", "<db_password>"); var settings = MongoClientSettings.FromConnectionString("<connection string>"); settings.Credential = credential; var mongoClient = new MongoClient(settings);
SCRAM-SHA-256
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.
You can specify the SCRAM-SHA-256
authentication mechanism with your connection
string as follow:
var mongoClient = new MongoClient("mongodb://<db_username>:<db_password>@<hostname>:<port>/?authSource=<authenticationDb>&authMechanism=SCRAM-SHA-256");
Tip
Default Mechanism
MongoDB version 4.0 and later uses SCRAM-SHA-256
as the default
authentication mechanism if the MongoDB server version supports it.
To learn more on specifying the default mechanism, see Default.
SCRAM-SHA-1
SCRAM-SHA-1
is s a salted challenge-response mechanism (SCRAM) that uses
your username and password, encrypted with the SHA-1
algorithm, to authenticate
your user.
You can specify the SCRAM-SHA-1
authentication mechanism with your connection
string as follow:
var mongoClient = new MongoClient("mongodb://<db_username>:<db_password>@<hostname>:<port>/?authSource=<authenticationDb>&authMechanism=SCRAM-SHA-1");
Tip
Default Mechanism
MongoDB version 4.0 uses SCRAM-SHA-1
as the default authentication mechanism
if the server does not support SCRAM-SHA-256
.
To learn more on specifying the default mechanism, see Default.
MONGODB-AWS
Note
The MONGODB-AWS
authentication mechanism is available only for
MongoDB deployments on MongoDB Atlas.
The MONGODB-AWS
authentication mechanism uses Amazon Web Services
Identity and Access Management (AWS IAM) credentials to authenticate a user to MongoDB.
To use AWS authentication, first perform the following steps:
Add the MongoDB.Driver.Authentication.AWS NuGet package to your project.
Add the following line of code to your application's bootstrap code to register the AWS authentication provider:
MongoClientSettings.Extensions.AddAWSAuthentication();
After you register the AWS authentication provider, you can either specify the AWS IAM credentials explicitly or instruct the driver to retrieve them automatically from an external source. The following sections describe both of these methods.
The code examples in these sections use the following placeholders:
<awsKeyId>
- value of the AWS access key ID<awsSecretKey>
- value of the AWS secret access key<awsSessionToken>
- value of the AWS session token
Tip
To learn more about configuring MongoDB Atlas with AWS IAM, see the Set Up Passwordless Authentication with AWS IAM Roles guide.
Specify Your AWS IAM Credentials
You can supply your AWS IAM credentials on a MongoClientSettings
object either by
using a MongoCredential
object or as part of the connection string. Select the
Connection String or MongoCredential tab to
see the corresponding syntax for specifying your credentials:
var connectionString = "mongodb+srv://<awsKeyId>:<awsSecretKey>@<hostname>[:<port>]?authSource=$external&authMechanism=MONGODB-AWS"; var mongoClientSettings = MongoClientSettings.FromConnectionString(connectionString); var client = new MongoClient(mongoClientSettings);
If you're using an AWS session token, include the authMechanismProperties
parameter in the connection string as shown below:
var connectionString = "mongodb+srv://<awsKeyId>:<awsSecretKey>@<hostname>[:<port>]?authSource=$external&authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:<awsSessionToken>";
var mongoClientSettings = MongoClientSettings.FromConnectionString("mongodb+srv://<hostname>[:<port>]"); mongoClientSettings.Credential = new MongoCredential("MONGODB-AWS", new MongoExternalIdentity("<awsKeyId>"), new PasswordEvidence("<awsSecretKey>")); var client = new MongoClient(mongoClientSettings);
If you're using an AWS session token, call the WithMechanismProperty()
method on your MongoCredential
object as shown below:
mongoClientSettings.Credential = new MongoCredential("MONGODB-AWS", new MongoExternalIdentity("<awsKeyId>"), new PasswordEvidence("<awsSecretKey>")) .WithMechanismProperty("AWS_SESSION_TOKEN", "<awsSessionToken>");
Retrieve Credentials Automatically
Instead of specifying your AWS IAM credentials in MongoClientSettings
, you can
instruct the .NET/C# Driver to use the AWS SDK to automatically retrieve your
credentials from an external source. To instruct the driver to
retrieve your credentials, perform the following actions:
Specify
MONGODB-AWS
as the authentication mechanismSpecify that the authentication source is external to MongoDB
Set your credentials in the appropriate location
You can specify the authentication mechanism and source either
by using a MongoCredential
object or as part of the connection string. Select the
Connection String or MongoCredential tab to
see the corresponding syntax for specifying the MONGODB-AWS
authentication mechanism
and external authentication source:
var connectionString = "mongodb+srv://<hostname>[:<port>]?authMechanism=MONGODB-AWS&authSource=$external"; var mongoClientSettings = MongoClientSettings.FromConnectionString(connectionString); var client = new MongoClient(mongoClientSettings);
var mongoClientSettings = MongoClientSettings.FromConnectionString("mongodb+srv://<hostname>[:<port>]"); mongoClientSettings.Credential = new MongoCredential("MONGODB-AWS", new MongoExternalAwsIdentity(), new ExternalEvidence()); var client = new MongoClient(mongoClientSettings);
After you specify the authentication mechanism and source, you must set your credentials in the location appropriate to the credential type. The .NET/C# Driver checks for credentials in the following locations in the order listed here:
Web identity provider
Shared AWS credentials file
Environment variables
ECS container credentials
EC2 container credentials
You can use an OpenID Connect (OIDC)-compatible web identity provider to authenticate
to Amazon Elastic Kubernetes Service (EKS) or other services.
To use a web identity provider, create a file that contains your
OIDC token, then set the absolute path to this file in an environment variable by using
bash
or a similar shell as shown in the following example:
export AWS_WEB_IDENTITY_TOKEN_FILE=<absolute path to file containing your OIDC token>
To authenticate by using a profile in a shared AWS credentials file, you can use a text editor, the AWS SDK for .NET, or the AWS CLI to create the appropriate credential file.
To retrieve credentials directly from environment variables, set the following
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>
Note
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 URI of your ECS
endpoint in an environment variable by using bash
or a similar shell.
Select the Full ECS URI or Relative ECS URI tab to
see the syntax for specifying the corresponding environment variable:
export AWS_CONTAINER_CREDENTIALS_FULL_URI=<full ECS endpoint>
export AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=<relative ECS endpoint>
To authenticate by using EC2 container credentials, make sure none of the environment variables mentioned earlier are set. The driver obtains the credentials from the default IPv4 EC2 instance metadata endpoint.
X.509
The X.509
authentication mechanism uses TLS
with X.509
certificates to authenticate your user, identified by the
distinguished names 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.
To learn more about using TLS/SSL, see our TLS/SSL guide.
To learn more about X.509
certificates, see the X.509 Server Manual Entry.
Select the Connection String or MongoCredential tab to
see the corresponding syntax for specifying the X.509
authentication mechanism:
var connectionString = "mongodb://<hostname>/?authMechanism=MONGODB-X509"; var settings = MongoClientSettings.FromConnectionString(connectionString); settings.useTls = true; settings.SslSettings = new SslSettings { ClientCertificates = new List<X509Certificate>() { new X509Certificate2("<path to X.509 certificate>", "<X.509 certificate password>") } };
var credential = MongoCredential.CreateMongoX509Credential("<X.509 certificate username>") var settings = new MongoClientSettings { Credential = credential SslSettings = new SslSettings { ClientCertificates = new List<X509Certificate>() { new X509Certificate2("<path to X.509 certificate>", "<X.509 certificate password>") }, }, UseTls = true, Server = new MongoServerAddress("<hostname", "<port>"), };
Tip
Username parameter
The username parameter provided to CreateMongoX509Credential
must
match the distinguished subject name of your X.509
certificate exactly.
You can alternatively pass null
as the parameter to prompt the MongoDB
server to infer the username based on your X.509
certificate.
Note
If you are using Windows, the driver might be unable to locate an X.509
authentication certificate created in memory. To learn more about a potential solution to
this issue, see the X.509 Credential Error
section of the Connection Troubleshooting guide.
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API Documentation: