From a54b2d77ce8b1e3fc69dc8d2b04745ef3f69e294 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Wed, 27 Nov 2024 09:13:12 -0600 Subject: [PATCH 1/3] Authentication refactor (#284) Co-authored-by: Rea Rustagi <85902999+rustagir@users.noreply.github.com> (cherry picked from commit bf67d808c3dc903d669f0891e611a57cd803f610) --- config/redirects | 3 + snooty.toml | 1 + source/connection-troubleshooting.txt | 23 +- source/fundamentals.txt | 4 +- source/fundamentals/authentication.txt | 437 +++-------------- .../fundamentals/authentication/aws-iam.txt | 248 ++++++++++ .../fundamentals/authentication/kerberos.txt | 221 +++++++++ source/fundamentals/authentication/ldap.txt | 90 ++++ source/fundamentals/authentication/oidc.txt | 231 +++++++++ source/fundamentals/authentication/scram.txt | 104 ++++ source/fundamentals/authentication/x509.txt | 147 ++++++ .../enterprise-authentication.txt | 449 ------------------ source/includes/comma-auth-options.rst | 6 + source/includes/troubleshooting/x509.rst | 18 + 14 files changed, 1127 insertions(+), 855 deletions(-) create mode 100644 source/fundamentals/authentication/aws-iam.txt create mode 100644 source/fundamentals/authentication/kerberos.txt create mode 100644 source/fundamentals/authentication/ldap.txt create mode 100644 source/fundamentals/authentication/oidc.txt create mode 100644 source/fundamentals/authentication/scram.txt create mode 100644 source/fundamentals/authentication/x509.txt delete mode 100644 source/fundamentals/enterprise-authentication.txt create mode 100644 source/includes/comma-auth-options.rst create mode 100644 source/includes/troubleshooting/x509.rst diff --git a/config/redirects b/config/redirects index fa71aef2..868b6e5a 100644 --- a/config/redirects +++ b/config/redirects @@ -14,3 +14,6 @@ raw: ${prefix}/master -> ${base}/upcoming/ [*-master]: ${prefix}/${version}/fundamentals/data-formats/polymorphism/ -> ${base}/${version}/fundamentals/serialization/polymorphic-objects/ [*-master]: ${prefix}/${version}/fundamentals/data-formats/bson/ -> ${base}/${version}/fundamentals/bson/ [*-master]: ${prefix}/${version}/fundamentals/class-mapping/ -> ${base}/${version}/fundamentals/serialization/class-mapping/ +[*-v2.30]: ${prefix}/${version}/upgrade/v2/ -> ${base}/${version}/upgrade/ +[*-v2.30]: ${prefix}/${version}/upgrade/v3/ -> ${base}/${version}/upgrade/ +[v3.0-*]: ${prefix}/${version}/fundamentals/enterprise-authentication/ -> ${base}/${version}/fundamentals/authentication/ diff --git a/snooty.toml b/snooty.toml index 97d459c8..7ae5f05a 100644 --- a/snooty.toml +++ b/snooty.toml @@ -6,6 +6,7 @@ toc_landing_pages = [ "/usage-examples", "/fundamentals", "/fundamentals/serialization", + "/fundamentals/authentication", "/upgrade", "/fundamentals/database-collection" ] diff --git a/source/connection-troubleshooting.txt b/source/connection-troubleshooting.txt index afac9f26..6e0877a6 100644 --- a/source/connection-troubleshooting.txt +++ b/source/connection-troubleshooting.txt @@ -182,28 +182,7 @@ the same machine doesn't require any authorization to connect. X.509 Credential Error ~~~~~~~~~~~~~~~~~~~~~~ -If you are using Windows as your operating system, you might encounter an issue in which the -{+driver-short+} is unable to locate an ``X.509`` authentication certificate in memory. -This error is raised with the following error message: - -.. code-block:: none - :copyable: false - - No credentials are available in the security package - -The following section describes a method that may help resolve the issue. - -Create and Store the Certificate On-Disk ----------------------------------------- - -Use the following code to generate any ``X.509`` certificates required by your application: - -.. code-block:: csharp - - using (X509Certificate2 certWithKey = certOnly.CopyWithPrivateKey(key)) - { - return new X509Certificate2(certWithKey.Export(X509ContentType.Pkcs12)); - } +.. include:: /includes/troubleshooting/x509.rst Error Sending Message ~~~~~~~~~~~~~~~~~~~~~ diff --git a/source/fundamentals.txt b/source/fundamentals.txt index 181bd766..78c0d727 100644 --- a/source/fundamentals.txt +++ b/source/fundamentals.txt @@ -18,7 +18,6 @@ Fundamentals Atlas Search Stable API Authentication - Enterprise Authentication Aggregation LINQ BSON Operations @@ -31,6 +30,7 @@ Fundamentals In-Use Encryption Search Geospatially Replica Set Operations + OData - :ref:`Connecting to MongoDB ` - :ref:`csharp-db-coll` @@ -39,7 +39,6 @@ Fundamentals - :ref:`csharp-atlas-search` - :ref:`csharp-stable-api` - :ref:`csharp-authentication-mechanisms` -- :ref:`csharp-enterprise-authentication-mechanisms` - :ref:`csharp-aggregation` - :ref:`csharp-linq` - :ref:`csharp-bson` @@ -52,3 +51,4 @@ Fundamentals - :ref:`Encrypt Fields ` - :ref:`csharp-geo` - :ref:`csharp-read-write-config` +- :ref:`csharp-odata` diff --git a/source/fundamentals/authentication.txt b/source/fundamentals/authentication.txt index 5ab13367..ee2da14a 100644 --- a/source/fundamentals/authentication.txt +++ b/source/fundamentals/authentication.txt @@ -17,392 +17,65 @@ Authentication Mechanisms .. meta:: :keywords: .NET, community, security +.. toctree:: + :caption: Authentication + + SCRAM + X.509 + AWS IAM + OIDC + LDAP (PLAIN) + Kerberos (GSSAPI) + Overview -------- -In this guide, you can learn how to authenticate with MongoDB using the -**authentication mechanisms** available in the {+mongo-community+}. +In this guide, you can learn how to authenticate to MongoDB by using the +**authentication mechanisms** available in {+mdb-server+}. 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 {+mongo-community+}: - -- :ref:`csharp-scram-sha-256` -- :ref:`csharp-scram-sha-1` -- :ref:`csharp-mongodb-aws` -- :ref:`csharp-x509` - -To authenticate using ``GSSAPI/Kerberos`` or ``LDAP``, see the -:ref:`csharp-enterprise-authentication-mechanisms` fundamentals page. For more -information on establishing a connection to your MongoDB cluster, see the -:ref:`csharp-connect-to-mongodb`. - -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: - -- ```` - MongoDB username. -- ```` - MongoDB user's password. -- ```` - network address of the MongoDB server, accessible by your client. -- ```` - port number of the MongoDB server. -- ```` - MongoDB database that contains the user's authentication - data. If you omit this parameter, the driver uses the default value ``admin``. - -.. _csharp-authentication-default: - -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`` -- ``MONGODB-CR`` - -.. note:: - - MongoDB version 4.0 uses SCRAM as the default mechanism, and no longer - supports ``MONGODB-CR``. - - -Select the :guilabel:`Connection String` or :guilabel:`MongoCredential` tab to -see the corresponding syntax for specifying the default authentication mechanism: - -.. tabs:: - - .. tab:: Connection String - :tabid: default-connection-string - - .. code-block:: csharp - - var mongoClient = new MongoClient("mongodb://:@:/?authSource="); - - .. tab:: MongoCredential - :tabid: default-mongo-credential - - .. code-block:: csharp - - var credential = MongoCredential.CreateCredential("", "", ""); - var settings = MongoClientSettings.FromConnectionString(""); - settings.Credential = credential; - var mongoClient = new MongoClient(settings); - -.. _csharp-scram-sha-256: - -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: - -.. code-block:: csharp - - var mongoClient = new MongoClient("mongodb://:@:/?authSource=&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 :ref:`csharp-authentication-default`. - -.. _csharp-scram-sha-1: - -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: - -.. code-block:: csharp - - var mongoClient = new MongoClient("mongodb://:@:/?authSource=&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 :ref:`csharp-authentication-default`. - -.. _csharp-mongodb-aws: - -MONGODB-AWS -~~~~~~~~~~~ - -.. note:: - - The ``MONGODB-AWS`` authentication mechanism is available only 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. You can either specify your credentials explicitly -or instruct the driver to retrieve them automatically from an external source. - -The following sections contain code examples that use the following placeholders: - -- ```` - value of the AWS access key ID -- ```` - value of the AWS secret access key -- ```` - value of the AWS session token - -.. tip:: - - To learn more about configuring MongoDB Atlas with AWS IAM, see the - :atlas:`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 -:guilabel:`Connection String` or :guilabel:`MongoCredential` tab to -see the corresponding syntax for specifying your credentials: - -.. tabs:: - - .. tab:: Connection String - :tabid: mongodb-aws-mongoclientsettings-connection-string - - .. code-block:: csharp - - var connectionString = "mongodb+srv://:@[:]?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: - - .. code-block:: csharp - - var connectionString = "mongodb+srv://:@[:]?authSource=$external&authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:"; - - .. tab:: MongoCredential - :tabid: mongodb-aws-mongoclientsettings-mongo-credential - - .. code-block:: csharp - - var mongoClientSettings = MongoClientSettings.FromConnectionString("mongodb+srv://[:]"); - mongoClientSettings.Credential = new MongoCredential("MONGODB-AWS", new MongoExternalIdentity(""), new PasswordEvidence("")); - var client = new MongoClient(mongoClientSettings); - - If you're using an AWS session token, call the ``WithMechanismProperty()`` - method on your ``MongoCredential`` object as shown below: - - .. code-block:: csharp - - mongoClientSettings.Credential = new MongoCredential("MONGODB-AWS", new MongoExternalIdentity(""), new PasswordEvidence("")) - .WithMechanismProperty("AWS_SESSION_TOKEN", ""); - -Retrieve Credentials Automatically -++++++++++++++++++++++++++++++++++ - -Instead of specifying your AWS IAM credentials in ``MongoClientSettings``, you can -instruct the {+driver-short+} 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 mechanism -- Specify 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 -:guilabel:`Connection String` or :guilabel:`MongoCredential` tab to -see the corresponding syntax for specifying the ``MONGODB-AWS`` authentication mechanism -and external authentication source: - -.. tabs:: - - .. tab:: Connection String - :tabid: mongodb-aws-automatic-connection-string - - .. code-block:: csharp - - var connectionString = "mongodb+srv://[:]?authMechanism=MONGODB-AWS&authSource=$external"; - var mongoClientSettings = MongoClientSettings.FromConnectionString(connectionString); - var client = new MongoClient(mongoClientSettings); - - .. tab:: MongoCredential - :tabid: mongodb-aws-automatic-mongo-credential - - .. code-block:: csharp - - var mongoClientSettings = MongoClientSettings.FromConnectionString("mongodb+srv://[:]"); - mongoClientSettings.Credential = new MongoCredential("MONGODB-AWS", new MongoExternalAwsIdentity(), new ExternalEvidence()); - var client = new MongoClient(mongoClientSettings); +.. tip:: Connecting to MongoDB -After you specify the authentication mechanism and source, you must set -your credentials in the location appropriate to the credential type. The {+driver-short+} -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: - -.. code-block:: bash - - export AWS_WEB_IDENTITY_TOKEN_FILE= - -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: - -.. code-block:: bash - - export AWS_ACCESS_KEY_ID= - export AWS_SECRET_ACCESS_KEY= - export AWS_SESSION_TOKEN= - -.. 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 :guilabel:`Full ECS URI` or :guilabel:`Relative ECS URI` tab to -see the syntax for specifying the corresponding environment variable: - -.. tabs:: - - .. tab:: Full ECS URI - :tabid: mongodb-aws-full-ecs-uri - - .. code-block:: bash - - export AWS_CONTAINER_CREDENTIALS_FULL_URI= - - .. tab:: Relative ECS URI - :tabid: mongodb-aws-relative-ecs-uri - - .. code-block:: bash - - export AWS_CONTAINER_CREDENTIALS_RELATIVE_URI= - -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. - -.. _csharp-x509: - -X.509 -~~~~~ - -The ``X.509`` authentication mechanism uses :wikipedia:`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 :ref:`TLS/SSL guide `. - -To learn more about ``X.509`` certificates, see the :ref:`X.509 Server Manual Entry `. - -Select the :guilabel:`Connection String` or :guilabel:`MongoCredential` tab to -see the corresponding syntax for specifying the ``X.509`` authentication mechanism: - -.. tabs:: - - .. tab:: Connection String - :tabid: default-connection-string - - .. code-block:: csharp - - var connectionString = "mongodb:///?authMechanism=MONGODB-X509"; - var settings = MongoClientSettings.FromConnectionString(connectionString); - - settings.useTls = true; - settings.SslSettings = new SslSettings - { - ClientCertificates = new List() - { - new X509Certificate2("", "") - } - }; - - .. tab:: MongoCredential - :tabid: default-mongo-credential - - .. code-block:: csharp - - var credential = MongoCredential.CreateMongoX509Credential("") - var settings = new MongoClientSettings - { - Credential = credential - SslSettings = new SslSettings - { - ClientCertificates = new List() - { - new X509Certificate2("", "") - }, - }, - UseTls = true, - Server = new MongoServerAddress(""), - }; - - .. note:: Certificate Type - - Your certificate must be a :wikipedia:`PKCS #12` type certificate - with a ``.p12`` extension. - - .. 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 :ref:`csharp-troubleshooting-connection-X509` - 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: - -- `MongoCredential() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoCredential.html>`__ -- `MongoClient() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClient.html>`__ -- `MongoClientSettings <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.html>`__ -- `CreateCredential() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoCredential.CreateCredential.html>`__ -- `CreateMongoX509Credential() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoCredential.CreateMongoX509Credential.html>`__ \ No newline at end of file + To learn how to establish a connection to your MongoDB deployment, see the + :ref:`csharp-connect-to-mongodb`. + +MongoDB Edition Compatibility +----------------------------- + +The following table lists the authentication mechanisms supported by MongoDB and +the {+mdb-server+} editions that each mechanism is compatible with. Click the name of +a mechanism to learn more about how to use it with your application. + +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + + * - Authentication Mechanism + - Atlas + - Enterprise Advanced + - Community + * - :ref:`` + - Yes + - Yes + - Yes + * - :ref:`` + - Yes + - Yes + - Yes + * - :ref:`` + - Yes + - No + - No + * - :ref:`OIDC (Workload Identity Federation) ` + - Yes + - Yes + - No + * - :ref:`` + - Yes + - Yes + - No + * - :ref:`Kerberos (GSSAPI) ` + - No + - Yes + - No diff --git a/source/fundamentals/authentication/aws-iam.txt b/source/fundamentals/authentication/aws-iam.txt new file mode 100644 index 00000000..1376ce81 --- /dev/null +++ b/source/fundamentals/authentication/aws-iam.txt @@ -0,0 +1,248 @@ +.. _csharp-mongodb-aws: +.. _csharp-authentication-aws: + +================================== +AWS Identity and Access Management +================================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 3 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: .NET, amazon web services, code example + +Overview +-------- + +The ``MONGODB-AWS`` authentication mechanism uses Amazon Web Services +Identity and Access Management (AWS IAM) credentials to authenticate a user to MongoDB. +You can use this mechanism only when authenticating to MongoDB Atlas. + +.. tip:: Configure Atlas for AWS IAM Authentication + + To learn more about configuring MongoDB Atlas for AWS IAM authentication, see + :atlas:`Set Up Authentication with AWS IAM ` in + the Atlas documentation. + +Code Placeholders +~~~~~~~~~~~~~~~~~ + +The code examples on this page use the following placeholders: + +- ````: The network address of your MongoDB Atlas deployment +- ````: Your AWS access key ID +- ````: Your AWS secret access key +- ````: Your AWS session token + +To use the code examples on this page, replace these placeholders with your own values. + +Using AWS IAM Authentication in Your Application +------------------------------------------------ + +To use AWS IAM authentication, perform the following steps: + +1. Add the `MongoDB.Driver.Authentication.AWS `__ + NuGet package to your project. You can add this package by using your IDE or by running + the following command in your terminal: + + .. code-block:: bash + + dotnet add package MongoDB.Driver.Authentication.AWS + +#. Add the following line of code to your application's bootstrap code to register the + AWS authentication provider: + + .. code-block:: csharp + :copyable: true + + MongoClientSettings.Extensions.AddAWSAuthentication(); + +After you register the AWS authentication provider, you can either specify your AWS IAM +credentials explicitly or instruct the driver to retrieve them automatically from an +external source. The following sections describe both of these methods. + +Specify AWS IAM Credentials Manually +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can supply your AWS IAM credentials in a ``MongoClientSettings`` object either by +using a ``MongoCredential`` object or as part of the connection string. Select the +:guilabel:`Connection String` or :guilabel:`MongoCredential` tab to +see the corresponding syntax for specifying your credentials: + +.. tabs:: + + .. tab:: Connection String + :tabid: mongodb-aws-mongoclientsettings-connection-string + + .. code-block:: csharp + + var connectionString = "mongodb+srv://:@?" + + "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: + + .. code-block:: csharp + + var connectionString = "mongodb+srv://:@?" + + "authSource=$external" + + "&authMechanism=MONGODB-AWS" + + "&authMechanismProperties=AWS_SESSION_TOKEN:"; + + .. tab:: MongoCredential + :tabid: mongodb-aws-mongoclientsettings-mongo-credential + + .. code-block:: csharp + + var mongoClientSettings = MongoClientSettings + .FromConnectionString("mongodb+srv://"); + mongoClientSettings.Credential = new MongoCredential( + "MONGODB-AWS", + new MongoExternalIdentity(""), + new PasswordEvidence("")); + var client = new MongoClient(mongoClientSettings); + + If you're using an AWS session token, call the ``WithMechanismProperty()`` + method on your ``MongoCredential`` object as shown below: + + .. code-block:: csharp + + mongoClientSettings.Credential = new MongoCredential( + "MONGODB-AWS", + new MongoExternalIdentity(""), + new PasswordEvidence("")) + .WithMechanismProperty("AWS_SESSION_TOKEN", ""); + +Retrieve AWS IAM Credentials Automatically +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Instead of specifying your AWS IAM credentials in ``MongoClientSettings``, you can +instruct the {+driver-short+} to use the AWS SDK to automatically retrieve your +credentials from an external source. + +To instruct the driver to retrieve your credentials, you must first specify ``MONGODB-AWS`` +as the authentication mechanism and specify that authentication source is external to +MongoDB. You can specify the authentication mechanism and source either +by using a ``MongoCredential`` object or as part of the connection string. Select the +:guilabel:`Connection String` or :guilabel:`MongoCredential` tab to +see the corresponding syntax for specifying the ``MONGODB-AWS`` authentication mechanism +and external authentication source: + +.. tabs:: + + .. tab:: Connection String + :tabid: mongodb-aws-automatic-connection-string + + .. code-block:: csharp + + var connectionString = "mongodb+srv://?" + + "authMechanism=MONGODB-AWS" + + "&authSource=$external"; + var mongoClientSettings = MongoClientSettings + .FromConnectionString(connectionString); + var client = new MongoClient(mongoClientSettings); + + .. tab:: MongoCredential + :tabid: mongodb-aws-automatic-mongo-credential + + .. code-block:: csharp + + var mongoClientSettings = MongoClientSettings + .FromConnectionString("mongodb+srv://"); + 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 {+driver-short+} +checks for credentials in the following locations in the order listed here. + +Web Identity Provider +````````````````````` + +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: + +.. code-block:: bash + + export AWS_WEB_IDENTITY_TOKEN_FILE= + +Shared AWS Credentials File +``````````````````````````` + +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. + +Environment Variables +````````````````````` + +To retrieve credentials directly from environment variables, set the following +environment variables by using ``bash`` or a similar shell: + +.. code-block:: bash + + export AWS_ACCESS_KEY_ID= + export AWS_SECRET_ACCESS_KEY= + export AWS_SESSION_TOKEN= + +.. note:: + + Omit the line containing ``AWS_SESSION_TOKEN`` if you don't need an AWS + session token for that role. + +ECS Container Credentials +````````````````````````` + +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 :guilabel:`Full ECS URI` or :guilabel:`Relative ECS URI` tab to +see the syntax for specifying the corresponding environment variable: + +.. tabs:: + + .. tab:: Full ECS URI + :tabid: mongodb-aws-full-ecs-uri + + .. code-block:: bash + + export AWS_CONTAINER_CREDENTIALS_FULL_URI= + + .. tab:: Relative ECS URI + :tabid: mongodb-aws-relative-ecs-uri + + .. code-block:: bash + + export AWS_CONTAINER_CREDENTIALS_RELATIVE_URI= + +EC2 Container Credentials +````````````````````````` + +To authenticate by using EC2 container credentials, make sure none of the +preceding environment variables are set. The driver obtains the +credentials from the default IPv4 EC2 instance metadata endpoint. + +API Documentation +----------------- + +To learn more about any of the methods or types discussed on this +page, see the following API documentation: + +- `MongoClient <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClient.html>`__ +- `MongoClientSettings <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.html>`__ +- `MongoCredential <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoCredential.html>`__ +- `AddAWSAuthentication() <{+new-api-root+}/MongoDB.Driver.Authentication.Aws/MongoDB.Driver.Authentication.AWS.ExtensionManagerExtensions.AddAWSAuthentication.html>`__ \ No newline at end of file diff --git a/source/fundamentals/authentication/kerberos.txt b/source/fundamentals/authentication/kerberos.txt new file mode 100644 index 00000000..1c289266 --- /dev/null +++ b/source/fundamentals/authentication/kerberos.txt @@ -0,0 +1,221 @@ +.. _csharp-kerberos: +.. _csharp-authentication-kerberos: + +================= +Kerberos (GSSAPI) +================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: .NET, code example + +Overview +-------- + +The Generic Security Services API (GSSAPI) authentication mechanism allows you to +use your principal name to authenticate to a Kerberos service. +You can use this mechanism only when authenticating to MongoDB Enterprise Advanced. + +Code Placeholders +~~~~~~~~~~~~~~~~~ + +The code examples on this page use the following placeholders: + +- ````: Your :wikipedia:`URL-encoded ` principal name. For + example: ``"username%40REALM.ME"`` +- ````: Your Kerberos user's password. +- ````: The network address of your MongoDB deployment. +- ````: The port number of your MongoDB deployment. If you omit this parameter, + the driver uses the default port number (``27017``). + +To use the code examples on this page, replace these placeholders with your own values. + +Using GSSAPI Authentication in Your Application +----------------------------------------------- + +You can specify the ``GSSAPI`` authentication mechanism and supply your Kerberos +credentials either by +using a ``MongoCredential`` object or as part of the connection string. +Select the :guilabel:`Connection String` or :guilabel:`MongoCredential` tab to +see the corresponding syntax: + +.. tabs:: + + .. tab:: Connection String + :tabid: connection-string + + .. code-block:: csharp + + var mongoClient = new MongoClient( + "mongodb://:@[:]/?authMechanism=GSSAPI"); + + .. tab:: MongoCredential + :tabid: mongo-credential + + .. code-block:: csharp + :emphasize-lines: 1 + + var credential = MongoCredential.CreateGssapiCredential("", ""); + var settings = MongoClientSettings.FromConnectionString(""); + settings.Credential = credential; + var mongoClient = new MongoClient(settings); + +.. tip:: Omitting the Password + + You can omit the password parameter if either of the following is true: + + - On Windows, the process owner running the application is the same as the + user needing authentication. + + - On Linux, the user has initialized their keytab via ``kinit username@REALM.COM``. + +Additional Properties +~~~~~~~~~~~~~~~~~~~~~ + +You can include the following GSSAPI configuration options in either your connection string +or your ``MongoCredential`` object. + +Fully Qualified Domain Name +``````````````````````````` + +The following example shows how to use the DNS server to retrieve the fully +qualified domain name of the host: + +.. tabs:: + + .. tab:: Connection String + :tabid: connection-string + + .. code-block:: csharp + + var mongoClient = new MongoClient( + "mongodb://:@[:]/?authMechanism=GSSAPI&" + + "authMechanismProperties=CANONICALIZE_HOSTNAME:true"); + + .. tab:: MongoCredential + :tabid: mongo-credential + + .. code-block:: csharp + :emphasize-lines: 1, 2 + + var credential = MongoCredential.CreateGssapiCredential("", ""); + credential = credential.WithMechanismProperty("CANONICALIZE_HOST_NAME", "true"); + + var settings = MongoClientSettings.FromConnectionString(""); + settings.Credential = credential; + var mongoClient = new MongoClient(settings); + +Realm +````` + +The following example shows how to specify the user's realm when it is different +from the service's realm. Replace the ```` placeholder with the +realm of the Kerberos user. + +.. tabs:: + + .. tab:: Connection String + :tabid: connection-string + + .. code-block:: csharp + + var mongoClient = new MongoClient( + "mongodb://:@[:]/?authMechanism=GSSAPI&" + + "authMechanismProperties=SERVICE_REALM:"); + + .. tab:: MongoCredential + :tabid: mongo-credential + + .. code-block:: csharp + :emphasize-lines: 1, 2 + + var credential = MongoCredential.CreateGssapiCredential("", ""); + credential = credential.WithMechanismProperty("SERVICE_REALM", ""); + + var settings = MongoClientSettings.FromConnectionString(""); + settings.Credential = credential; + var mongoClient = new MongoClient(settings); + +Service Name +```````````` + +The following example shows how to specify the service name when it is not the +default ``mongodb``. Replace the ```` placeholder with the name of +the service. + +.. tabs:: + + .. tab:: Connection String + :tabid: connection-string + + .. code-block:: csharp + + var mongoClient = new MongoClient( + "mongodb://:@[:]/?authMechanism=GSSAPI&" + + "authMechanismProperties=SERVICE_NAME:"); + + .. tab:: MongoCredential + :tabid: mongo-credential + + .. code-block:: csharp + :emphasize-lines: 1, 2 + + var credential = MongoCredential.CreateGssapiCredential("", ""); + credential = credential.WithMechanismProperty("SERVICE_NAME", ""); + + var settings = MongoClientSettings.FromConnectionString(""); + settings.Credential = credential; + var mongoClient = new MongoClient(settings); + +Multiple Properties +``````````````````` + +The following example shows how to specify multiple authentication mechanism +properties: + +.. tabs:: + + .. tab:: Connection String + :tabid: connection-string + + .. code-block:: csharp + + var mongoClient = new MongoClient( + "mongodb://:@[:]/?authMechanism=GSSAPI&" + + "authMechanismProperties=SERVICE_NAME:,SERVICE_REALM:"); + + .. tab:: MongoCredential + :tabid: mongo-credential + + .. code-block:: csharp + :emphasize-lines: 2, 3 + + var credential = MongoCredential.CreateGssapiCredential("", ""); + credential = credential + .WithMechanismProperty("SERVICE_REALM", "") + .WithMechanismProperty("SERVICE_NAME", ""); + + var settings = MongoClientSettings.FromConnectionString(""); + settings.Credential = credential; + var mongoClient = new MongoClient(settings); + +API Documentation +----------------- + +To learn more about any of the methods or types discussed on this +page, see the following API documentation: + +- `MongoClient <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClient.html>`__ +- `MongoClientSettings <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.html>`__ +- `MongoCredential <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoCredential.html>`__ +- `CreateGssapiCredential() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoCredential.CreateGssapiCredential.html>`__ +- `WithMechanismProperty() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoCredential.WithMechanismProperty.html>`__ \ No newline at end of file diff --git a/source/fundamentals/authentication/ldap.txt b/source/fundamentals/authentication/ldap.txt new file mode 100644 index 00000000..0303356f --- /dev/null +++ b/source/fundamentals/authentication/ldap.txt @@ -0,0 +1,90 @@ +.. _csharp-authentication-LDAP: +.. _csharp-authentication-ldap: + +==== +LDAP +==== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: .NET, code example + +Overview +-------- + +The PLAIN authentication mechanism allows you to use your Lightweight Directory Access +Protocol (LDAP) username and password to authenticate to MongoDB. +You can use this mechanism only when authenticating to MongoDB Enterprise Advanced. + +.. tip:: PLAIN Authentication + + LDAP authentication uses the PLAIN Simple Authentication and Security Layer + (SASL) defined in `RFC-4616 `__. + +Code Placeholders +~~~~~~~~~~~~~~~~~ + +The code examples on this page use the following placeholders: + +- ````: Your LDAP username. +- ````: Your LDAP password. +- ````: The network address of your MongoDB deployment. +- ````: The port number of your MongoDB deployment. If you omit this parameter, + the driver uses the default port number (``27017``). You don't need to specify a port + when connecting to a MongoDB Atlas cluster. +- ````: The MongoDB database that contains the user's LDAP credentials. + If you omit this parameter, the driver uses the default database (``admin``). + +To use the code examples on this page, replace these placeholders with your own values. + +Using PLAIN Authentication in Your Application +---------------------------------------------- + +You can specify the ``PLAIN`` authentication mechanism and supply your LDAP credentials +either by +using a ``MongoCredential`` object or as part of the connection string. +Select the :guilabel:`Connection String` or :guilabel:`MongoCredential` tab to +see the corresponding syntax: + +.. tabs:: + + .. tab:: Connection String + :tabid: connection-string + + .. code-block:: csharp + + var mongoClient = new MongoClient( + "mongodb://:@[:]/?authSource=" + + "&authMechanism=PLAIN"); + + .. tab:: MongoCredential + :tabid: mongo-credential + + .. code-block:: csharp + :emphasize-lines: 1 + + var credential = MongoCredential + .CreatePlainCredential("", "", ""); + var settings = MongoClientSettings.FromConnectionString(""); + settings.Credential = credential; + var mongoClient = new MongoClient(settings); + +API Documentation +----------------- + +To learn more about any of the methods or types discussed on this +page, see the following API documentation: + +- `MongoClient <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClient.html>`__ +- `MongoClientSettings <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.html>`__ +- `MongoCredential <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoCredential.html>`__ +- `CreatePlainCredential() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoCredential.CreatePlainCredential.html>`__ \ No newline at end of file diff --git a/source/fundamentals/authentication/oidc.txt b/source/fundamentals/authentication/oidc.txt new file mode 100644 index 00000000..dae82f66 --- /dev/null +++ b/source/fundamentals/authentication/oidc.txt @@ -0,0 +1,231 @@ +.. _csharp-mongodb-oidc: +.. _csharp-authentication-oidc: + +=================================== +OIDC (Workload Identity Federation) +=================================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: .NET, code example + +Overview +-------- + +The OpenID Connect (OIDC) authentication mechanism allows you to authenticate to +MongoDB by using a third-party identity provider, such as Azure or Google Cloud +Platform (GCP). + +You can use this mechanism only when authenticating to MongoDB Atlas or MongoDB +Enterprise Advanced, and only when authenticating to MongoDB v7.0 or later. + +.. tip:: OIDC Authentication + + To learn more about configuring MongoDB Atlas for OIDC authentication, see + :atlas:`Set up Workforce Identity Federation with OIDC ` + in the Atlas documentation. + + For more information about using OIDC authentication with MongoDB, see + :manual:`OpenID Connect Authentication ` and + :manual:`MongoDB Server Parameters ` + in the {+mdb-server+} manual. + +Code Placeholders +~~~~~~~~~~~~~~~~~ + +The code examples on this page use the following placeholders: + +- ``+srv``: Include this option in your connection string prefix only if you are connecting + to a MongoDB Atlas cluster. To learn more about the ``+srv`` option, see + :manual:`Connection String Formats ` + in the {+mdb-server+} manual. +- ````: The client ID or application ID of the Azure managed identity or + enterprise application, if authenticating against Azure IMDS. +- ````: The network address of your MongoDB deployment. +- ````: The port number of your MongoDB deployment. If you omit this parameter, + the driver uses the default port number (``27017``). You don't need to specify a port + when connecting to a MongoDB Atlas cluster. +- ````: The audience parameter configured on your MongoDB deployment. + +To use the code examples on this page, replace these placeholders with your own values. + +Using OIDC Authentication in Your Application +--------------------------------------------- + +The following sections describe how to use OIDC authentication to +authenticate from various platforms. + +.. _csharp-mongodb-oidc-azure-imds: + +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 {+driver-short+}'s built-in Azure +support. + +You can specify Azure IMDS OIDC authentication on a ``MongoClientSettings`` object either by +using a ``MongoCredential`` object or as part of the connection string. Select the +:guilabel:`Connection String` or :guilabel:`MongoCredential` tab to +see the corresponding syntax. + +.. include:: /includes/comma-auth-options.rst + +.. tabs:: + + .. tab:: Connection String + :tabid: mongodb-azure-imds-connection-string + + The following code example shows how to specify Azure IMDS OIDC authentication. + Replace the ```` placeholder with the percent-encoded + value of the ``audience`` parameter configured on your MongoDB deployment. + + .. code-block:: csharp + + var connectionString = "mongodb://@[:]/?" + + "authMechanism=MONGODB-OIDC" + + "&authMechanismProperties=ENVIRONMENT:azure,TOKEN_RESOURCE:"); + var mongoClientSettings = MongoClientSettings.FromConnectionString(connectionString); + var client = new MongoClient(mongoClientSettings); + + .. tab:: MongoCredential + :tabid: mongodb-azure-mongo-credential + + The following code example shows how to specify Azure IMDS OIDC authentication: + + .. code-block:: csharp + + var mongoClientSettings = MongoClientSettings.FromConnectionString( + "mongodb://[:]"); + mongoClientSettings.Credential = MongoCredential + .CreateOidcCredential("azure", "") + .WithMechanismProperty("TOKEN_RESOURCE", ""); + var client = new MongoClient(mongoClientSettings); + +.. _csharp-mongodb-oidc-gcp-imds: + +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 {+driver-short+}'s built-in GCP +support. + +You can specify GCP IMDS OIDC authentication on a ``MongoClientSettings`` object either by +using a ``MongoCredential`` object or as part of the connection string. Select the +:guilabel:`Connection String` or :guilabel:`MongoCredential` tab to +see the corresponding syntax. + +.. include:: /includes/comma-auth-options.rst + +.. tabs:: + + .. tab:: Connection String + :tabid: mongodb-gcp-imds-connection-string + + The following code example shows how to specify GCP IMDS OIDC authentication as + part of the authentication string: + + .. code-block:: csharp + + var connectionString = "mongodb://[:]/?authMechanism=MONGODB-OIDC" + + "&authMechanismProperties=ENVIRONMENT:gcp,TOKEN_RESOURCE:"); + var mongoClientSettings = MongoClientSettings.FromConnectionString(connectionString); + var client = new MongoClient(mongoClientSettings); + + .. tab:: MongoCredential + :tabid: mongodb-gcp-mongo-credential + + The following code example shows how to specify GCP IMDS OIDC authentication by using + a ``MongoCredential`` object: + + .. code-block:: csharp + + var mongoClientSettings = MongoClientSettings.FromConnectionString( + "mongodb://[:]"); + mongoClientSettings.Credential = MongoCredential + .CreateOidcCredential("gcp") + .WithMechanismProperty("TOKEN_RESOURCE", ""); + var client = new MongoClient(mongoClientSettings); + +Custom Callback +~~~~~~~~~~~~~~~ + +The {+driver-short+} 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 class that implements the ``IOidcCallback`` interface. This interface +contains two methods: + +- ``GetOidcAccessToken()``: This method accepts the parameters to the callback method + and returns the callback response. +- ``GetOidcAccessTokenAsync()``: This method is an asynchronous version of the previous + method. + +The following code is an example implementation of the ``IOidcCallback`` interface. +In this example, the methods retrieve an OIDC token from a file named ``"access-token.dat"`` +in the local file system. + +.. code-block:: csharp + + public class MyCallback : IOidcCallback + { + public OidcAccessToken GetOidcAccessToken( + OidcCallbackParameters parameters, + CancellationToken cancellationToken) + { + var accessToken = File.ReadAllText("access-token.dat"); + return new(accessToken, expiresIn: null); + } + + public async Task GetOidcAccessTokenAsync( + OidcCallbackParameters parameters, + CancellationToken cancellationToken) + { + var accessToken = await File.ReadAllTextAsync( + "access-token.dat", + cancellationToken) + .ConfigureAwait(false); + return new(accessToken, expiresIn: null); + } + } + +After you define a class that contains your custom callback methods, call the +``MongoCredential.CreateOidcCredential()`` method and pass in a new instance of your +class. Store the result of this method call in the ``Credential`` property of your +``MongoClientSettings`` object, as shown in the following code example: + +.. code-block:: csharp + + var mongoClientSettings = MongoClientSettings + .FromConnectionString("mongodb://[:]"); + mongoClientSettings.Credential = MongoCredential.CreateOidcCredential(new MyCallback()); + var client = new MongoClient(mongoClientSettings); + +API Documentation +----------------- + +To learn more about any of the methods or types discussed on this +page, see the following API documentation: + +- `MongoClient() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClient.html>`__ +- `MongoClientSettings() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.html>`__ +- `MongoCredential() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoCredential.html>`__ +- `MongoClientSettings.Extensions.AddAWSAuthentication() <{+new-api-root+}/MongoDB.Driver/MongoClientSettings.Extensions.html#MongoDB_Driver_MongoClientSettings_Extensions_AddAWSAuthentication>`__ +- `CreateOidcCredential() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoCredential.CreateOidcCredential.html>`__ +- `WithMechanismProperty() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoCredential.CreateOidcCredential.html#MongoDB_Driver_MongoDB_Driver_MongoCredential_WithMechanismProperty>`__ +- `IOidcCallback <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core/Authentication/IOidcCallback.html>`__ +- `OidcAccessToken <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core/Authentication/OidcAccessToken.html>`__ +- `OidcCallbackParameters <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core/Authentication/OidcCallbackParameters.html>`__ \ No newline at end of file diff --git a/source/fundamentals/authentication/scram.txt b/source/fundamentals/authentication/scram.txt new file mode 100644 index 00000000..64d047ad --- /dev/null +++ b/source/fundamentals/authentication/scram.txt @@ -0,0 +1,104 @@ +.. _csharp-authentication-scram: + +===== +SCRAM +===== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: .NET, salt, default, code example + +Overview +-------- + +**Salted Challenge Response Authentication Mechanism (SCRAM)** is a family of +authentication mechanisms that use a challenge-response mechanism to authenticate +the user. SCRAM-SHA-256, which uses the SHA-256 algorithm to hash your password, is the +default authentication mechanism in {+mdb-server+} version 4.0 +and later. SCRAM-SHA-1, which uses the SHA-1 algorithm instead, is the default +authentication mechanism in {+mdb-server+} versions earlier than 4.0. + +You can use SCRAM to authenticate to MongoDB Atlas, MongoDB +Enterprise Advanced, and MongoDB Community Edition. + +.. tip:: SCRAM Mechanisms + + To learn more about the SCRAM family of authentication mechanisms, see + `RFC 5802 `__ and + :wikipedia:`Salted Challenge Response Authentication Mechanism ` + on Wikipedia. + + For more information about the MongoDB implementation of SCRAM, see + :manual:`SCRAM ` in the {+mdb-server+} manual. + +Code Placeholders +~~~~~~~~~~~~~~~~~ + +The code examples on this page use the following placeholders: + +- ``+srv``: Include this option in your connection string prefix only if you are connecting + to a MongoDB Atlas cluster. To learn more about the ``+srv`` option, see + :manual:`Connection String Formats ` + in the {+mdb-server+} manual. +- ````: The MongoDB username of the user to authenticate. +- ````: The MongoDB password of the user to authenticate. +- ````: The network address of your MongoDB deployment. +- ````: The port number of your MongoDB deployment. If you omit this parameter, + the driver uses the default port number (``27017``). You don't need a port number + when connecting to a MongoDB Atlas cluster. +- ````: The MongoDB database that contains the user's authentication + data. If you omit this parameter, the driver uses the default value, ``admin``. + +To use the code examples on this page, replace these placeholders with your own values. + +Using SCRAM Authentication in Your Application +---------------------------------------------- + +To use SCRAM to authenticate your MongoDB user, specify your +MongoDB credentials, but don't specify an authentication mechanism. +You can specify your MongoDB +credentials either in your connection string or by using a ``MongoCredential`` object. +Select the :guilabel:`Connection String` or :guilabel:`MongoCredential` tab to +see the corresponding syntax: + +.. tabs:: + + .. tab:: Connection String + :tabid: default-connection-string + + .. code-block:: csharp + + var mongoClient = new MongoClient( + "mongodb[+srv]://:@[:]/?" + + "authSource="); + + .. tab:: MongoCredential + :tabid: default-mongo-credential + + .. code-block:: csharp + + var credential = MongoCredential + .CreateCredential("", "", ""); + var settings = MongoClientSettings.FromConnectionString(""); + settings.Credential = credential; + var mongoClient = new MongoClient(settings); + +API Documentation +----------------- + +To learn more about any of the methods or types discussed on this +page, see the following API documentation: + +- `MongoCredential <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoCredential.html>`__ +- `MongoClient <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClient.html>`__ +- `MongoClientSettings <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.html>`__ +- `CreateCredential() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoCredential.CreateCredential.html>`__ \ No newline at end of file diff --git a/source/fundamentals/authentication/x509.txt b/source/fundamentals/authentication/x509.txt new file mode 100644 index 00000000..4d61fb4e --- /dev/null +++ b/source/fundamentals/authentication/x509.txt @@ -0,0 +1,147 @@ +.. _csharp-authentication-x509: + +===== +X.509 +===== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: .NET, certificate, code example + +Overview +-------- + +In the **X.509** authentication mechanism, the server and client use the +:wikipedia:`TLS ` protocol to exchange X.509 public-key +certificates. You can use this mechanism to authenticate to MongoDB Atlas, MongoDB +Enterprise Advanced, and MongoDB Community Edition. + +.. tip:: X.509 Mechanism + + To learn how to use TLS/SSL with the {+driver-short+}, + see :ref:`TLS/SSL `. + + For more information about X.509 certificates, see + :ref:`X.509 ` in the {+mdb-server+} manual. + +Code Placeholders +~~~~~~~~~~~~~~~~~ + +The code examples on this page use the following placeholders: + +- ``+srv``: Include this option in your connection string prefix only if you are connecting + to a MongoDB Atlas cluster. To learn more about the ``+srv`` option, see + :manual:`Connection String Formats ` + in the {+mdb-server+} manual. +- ````: The network address of your MongoDB deployment. +- ````: The port number of the MongoDB deployment. If you omit this parameter, + the driver uses the default port number (``27017``). You don't need a port number + when connecting to a MongoDB Atlas cluster. +- ````: The username of the user associated with the X.509 + certificate. The username must match the distinguished subject name of the certificate. + If you omit this parameter, the MongoDB deployment infers the username + from the X.509 certificate. +- ````: The path to the X.509 certificate file. +- ````: The password for the X.509 certificate. + +To use the code examples on this page, replace these placeholders with your own values. + +Using X.509 Authentication in Your Application +---------------------------------------------- + +To use an X.509 certificate for authentication, you must use a +``MongoClientSettings`` object to specify +the path to your X.509 certificate and the password for the certificate. The certificate +must use the :wikipedia:`PKCS #12` (``.p12``) format. + +.. tip:: Convert .pem to .p12 + + If your certificate uses the :wikipedia:`PEM` (``.pem``) format, + you must convert it to the ``.p12`` format. To convert the certificate, use the + ``openssl`` command-line tool, as shown in the following code example: + + .. code-block:: bash + + openssl pkcs12 -export -out <.p12 file> -inkey -in <.pem file> + + For more information about ``openssl-pkcs12``, see the + `OpenSSL documentation. `__ + +You must also specify ``MONGODB-X509`` as the authentication mechanism and ``$external`` +as the authentication source. You can specify +these options either in your connection string or by using a ``MongoCredential`` object. +Select the :guilabel:`Connection String` or :guilabel:`MongoCredential` tab to +see the corresponding syntax: + +.. tabs:: + + .. tab:: Connection String + :tabid: default-connection-string + + .. code-block:: csharp + + var connectionString = "mongodb[+srv]://[:]/?authSource=$external&authMechanism=MONGODB-X509"; + var settings = MongoClientSettings.FromConnectionString(connectionString); + + settings.UseTls = true; + settings.SslSettings = new SslSettings + { + ClientCertificates = new List() + { + new X509Certificate2("", "") + } + }; + + .. tab:: MongoCredential + :tabid: default-mongo-credential + + .. code-block:: csharp + + var credential = MongoCredential.CreateMongoX509Credential(""); + var settings = new MongoClientSettings + { + Credential = credential, + SslSettings = new SslSettings + { + ClientCertificates = new List() + { + new X509Certificate2("", "") + }, + }, + UseTls = true, + Server = new MongoServerAddress(""[, ""]), + }; + +Troubleshooting +--------------- + +.. include:: /includes/troubleshooting/x509.rst + +API Documentation +----------------- + +To learn more about any of the MongoDB methods and types used on this +page, see the following API documentation: + +- `MongoClient <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClient.html>`__ +- `MongoClientSettings <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.html>`__ +- `MongoCredential <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoCredential.html>`__ +- `SslSettings <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.SslSettings.html>`__ +- `MongoServerAddress <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoServerAddress.html>`__ +- `CreateMongoX509Credential() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoCredential.CreateMongoX509Credential.html>`__ + +For more information about the .NET types used on this page, see the +following MSDN documentation: + +- `X509Certificate `__ +- `X509Certificate2 `__ + diff --git a/source/fundamentals/enterprise-authentication.txt b/source/fundamentals/enterprise-authentication.txt deleted file mode 100644 index fdc07b44..00000000 --- a/source/fundamentals/enterprise-authentication.txt +++ /dev/null @@ -1,449 +0,0 @@ -.. _csharp-enterprise-authentication-mechanisms: - -==================================== -Enterprise Authentication Mechanisms -==================================== - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -Overview --------- - -In this guide, you can learn how to authenticate with MongoDB using the -**authentication mechanisms** available only in the {+mongo-enterprise+}. -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 -{+mongo-enterprise+}. - -- :ref:`GSSAPI/Kerberos ` -- :ref:`LDAP (Plain) ` -- :ref:`MONGODB-OIDC ` - -To authenticate using another mechanism, see the -:ref:`` fundamentals page. For -more information on establishing a connection to your MongoDB cluster, see the -:ref:`csharp-connect-to-mongodb`. - -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. - -.. _csharp-kerberos: - -Authenticate with GSSAPI/Kerberos ---------------------------------- - -The Generic Security Services API (GSSAPI) authentication mechanism allows the -user to authenticate to a Kerberos service using the user's principal name. - -The following examples specify the authentication mechanism using the following -placeholders: - -- ````: Your :wikipedia:`URL-encoded ` principal name; for example "username%40REALM.ME" -- ````: Your Kerberos user's password -- ````: The network address of your MongoDB server, accessible by your client - -Select the :guilabel:`Connection String` or :guilabel:`MongoCredential` tab to -see the corresponding syntax for specifying the GSSAPI/Kerberos authentication -mechanism: - -.. tabs:: - - .. tab:: Connection String - :tabid: connection-string - - .. code-block:: csharp - - var mongoClient = new MongoClient("mongodb://:@/?authMechanism=GSSAPI"); - - .. tab:: MongoCredential - :tabid: mongo-credential - - .. code-block:: csharp - :emphasize-lines: 1 - - var credential = MongoCredential.CreateGssapiCredential("", ""); - var settings = MongoClientSettings.FromConnectionString(""); - settings.Credential = credential; - var mongoClient = new MongoClient(settings); - -.. tip:: Omitting the Password - - You can omit the password if one of the following are true: - - - On Windows, the process owner running the application is the same as the - user needing authentication. - - - On Linux, the user has initialized their keytab via ``kinit username@REALM.COM``. - -Additional Properties -~~~~~~~~~~~~~~~~~~~~~ - -You can specify additional properties with your authentication -mechanism using the connection string or a factory method in the ``MongoCredential`` -class. - -Fully Qualified Domain Name -``````````````````````````` - -The following example shows how to use the DNS server to retrieve the fully -qualified domain name of the host: - -.. tabs:: - - .. tab:: Connection String - :tabid: connection-string - - .. code-block:: csharp - - var mongoClient = new MongoClient("mongodb://:@/?authMechanism=GSSAPI&authMechanismProperties=CANONICALIZE_HOSTNAME:true"); - - .. tab:: MongoCredential - :tabid: mongo-credential - - .. code-block:: csharp - :emphasize-lines: 1, 2 - - var credential = MongoCredential.CreateGssapiCredential("", ""); - credential = credential.WithMechanismProperty("CANONICALIZE_HOST_NAME", "true"); - - var settings = MongoClientSettings.FromConnectionString(""); - settings.Credential = credential; - var mongoClient = new MongoClient(settings); - -Realm -````` - -The following example shows how to specify the user's realm when it is different -from the service's realm: - -.. tabs:: - - .. tab:: Connection String - :tabid: connection-string - - .. code-block:: csharp - - var mongoClient = new MongoClient("mongodb://:@/?authMechanism=GSSAPI&authMechanismProperties=SERVICE_REALM:"); - - .. tab:: MongoCredential - :tabid: mongo-credential - - .. code-block:: csharp - :emphasize-lines: 1, 2 - - var credential = MongoCredential.CreateGssapiCredential("", ""); - credential = credential.WithMechanismProperty("SERVICE_REALM", ""); - - var settings = MongoClientSettings.FromConnectionString(""); - settings.Credential = credential; - var mongoClient = new MongoClient(settings); - -Service name -```````````` - -The following example shows how to specify the service name when it is not the -default ``mongodb``: - -.. tabs:: - - .. tab:: Connection String - :tabid: connection-string - - .. code-block:: csharp - - var mongoClient = new MongoClient("mongodb://:@/?authMechanism=GSSAPI&authMechanismProperties=SERVICE_NAME:"); - - .. tab:: MongoCredential - :tabid: mongo-credential - - .. code-block:: csharp - :emphasize-lines: 1, 2 - - var credential = MongoCredential.CreateGssapiCredential("", ""); - credential = credential.WithMechanismProperty("SERVICE_NAME", ""); - - var settings = MongoClientSettings.FromConnectionString(""); - settings.Credential = credential; - var mongoClient = new MongoClient(settings); - -Multiple properties -``````````````````` - -The following example shows how to specify multiple authentication mechanism -properties: - -.. tabs:: - - .. tab:: Connection String - :tabid: connection-string - - .. code-block:: csharp - - var mongoClient = new MongoClient("mongodb://:@/?authMechanism=GSSAPI&authMechanismProperties=SERVICE_NAME:,SERVICE_REALM:"); - - .. tab:: MongoCredential - :tabid: mongo-credential - - .. code-block:: csharp - :emphasize-lines: 2, 3 - - var credential = MongoCredential.CreateGssapiCredential("", ""); - credential = credential.WithMechanismProperty("SERVICE_REALM", "") - .WithMechanismProperty("SERVICE_NAME", ""); - - var settings = MongoClientSettings.FromConnectionString(""); - settings.Credential = credential; - var mongoClient = new MongoClient(settings); - -.. _csharp-LDAP: - -Authenticate with LDAP (PLAIN) ------------------------------- - -You can authenticate to a Lightweight Directory Access Protocol (LDAP) server -using your directory-server username and password. - -The following examples specify the authentication mechanism using the following -placeholders: - -- ````: Your LDAP username -- ````: Your LDAP password -- ````: The network address of your MongoDB server, accessible by your - client -- ````: The MongoDB database that contains your user's - authentication - -Select the :guilabel:`Connection String` or :guilabel:`MongoCredential` tab to -see the corresponding syntax for specifying the LDAP authentication -mechanism: - -.. tabs:: - - .. tab:: Connection String - :tabid: connection-string - - .. code-block:: csharp - - var mongoClient = new MongoClient("mongodb://:@/?authSource=&authMechanism=PLAIN"); - - .. tab:: MongoCredential - :tabid: mongo-credential - - .. code-block:: csharp - :emphasize-lines: 1 - - var credential = MongoCredential.CreatePlainCredential("", "", ""); - var settings = MongoClientSettings.FromConnectionString(""); - settings.Credential = credential; - var mongoClient = new MongoClient(settings); - - .. tip:: - - The method refers to PLAIN instead of LDAP since it - authenticates using the PLAIN Simple Authentication and Security Layer - (SASL) defined in `RFC-4616 `__. - -.. _csharp-mongodb-oidc: - -MONGODB-OIDC ------------- - -.. important:: - - The MONGODB-OIDC authentication mechanism requires {+mdb-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 -:manual:`OpenID Connect Authentication ` and -:manual:`MongoDB Server Parameters ` -in the {+mdb-server+} manual. - -.. _csharp-mongodb-oidc-azure-imds: - -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 {+driver-short+}'s built-in Azure -support. - -You can specify Azure IMDS OIDC authentication on a ``MongoClientSettings`` object either by -using a ``MongoCredential`` object or as part of the connection string. Select the -:guilabel:`Connection String` or :guilabel:`MongoCredential` tab to -see the corresponding syntax. - -.. tabs:: - - .. tab:: Connection String - :tabid: mongodb-azure-imds-connection-string - - The following code example shows how to specify Azure IMDS OIDC authentication. - Replace the ```` placeholder with the percent-encoded - value of the ``audience`` parameter configured on your MongoDB deployment. - - You cannot pass values containing the comma (``,``) character to the ``authMechanismProperties`` - option. You must specify values that contain commas in a ``MongoCredential`` object, - as demonstrated in the :guilabel:`MongoCredential` tab. - - .. code-block:: csharp - - var connectionString = "mongodb://@[:]/?" + - "authMechanism=MONGODB-OIDC" + - "&authMechanismProperties=ENVIRONMENT:azure,TOKEN_RESOURCE:"); - var mongoClientSettings = MongoClientSettings.FromConnectionString(connectionString); - var client = new MongoClient(mongoClientSettings); - - .. tab:: MongoCredential - :tabid: mongodb-azure-mongo-credential - - The following code example shows how to specify Azure IMDS OIDC authentication. - Replace the ```` placeholder with the client ID or application ID of the - Azure managed identity or enterprise application. Replace the ```` - placeholder with the value of the ``audience`` parameter configured on your MongoDB - deployment. - - .. code-block:: csharp - - var mongoClientSettings = MongoClientSettings.FromConnectionString( - "mongodb+srv://[:]"); - mongoClientSettings.Credential = MongoCredential.CreateOidcCredential("azure", "") - .WithMechanismProperty("TOKEN_RESOURCE", ""); - var client = new MongoClient(mongoClientSettings); - -.. _csharp-mongodb-oidc-gcp-imds: - -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 {+driver-short+}'s built-in GCP -support. - -You can specify GCP IMDS OIDC authentication on a ``MongoClientSettings`` object either by -using a ``MongoCredential`` object or as part of the connection string. Select the -:guilabel:`Connection String` or :guilabel:`MongoCredential` tab to -see the corresponding syntax. - -.. tabs:: - - .. tab:: Connection String - :tabid: mongodb-gcp-imds-connection-string - - The following code example shows how to specify GCP IMDS OIDC authentication as - part of the authentication string. - Replace the ```` placeholder with the - value of the ``audience`` parameter configured on your MongoDB deployment. - - You cannot pass values containing the comma (``,``) character to the ``authMechanismProperties`` - option. You must specify values that contain commas in a ``MongoCredential`` object, - as demonstrated in the :guilabel:`MongoCredential` tab. - - .. code-block:: csharp - - var connectionString = "mongodb://[:]/?" + - "authMechanism=MONGODB-OIDC" + - "&authMechanismProperties=ENVIRONMENT:gcp,TOKEN_RESOURCE:"); - var mongoClientSettings = MongoClientSettings.FromConnectionString(connectionString); - var client = new MongoClient(mongoClientSettings); - - .. tab:: MongoCredential - :tabid: mongodb-gcp-mongo-credential - - The following code example shows how to specify GCP IMDS OIDC authentication by using - a ``MongoCredential`` object. - Replace the ```` - placeholder with the value of the ``audience`` parameter configured on your MongoDB - deployment. - - .. code-block:: csharp - - var mongoClientSettings = MongoClientSettings.FromConnectionString( - "mongodb+srv://[:]"); - mongoClientSettings.Credential = MongoCredential.CreateOidcCredential("gcp") - .WithMechanismProperty("TOKEN_RESOURCE", ""); - var client = new MongoClient(mongoClientSettings); - -Custom Callback -~~~~~~~~~~~~~~~ - -The {+driver-short+} 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 class that implements the ``IOidcCallback`` interface. This interface -contains two methods: - -- ``GetOidcAccessToken()``: This method accepts the parameters to the callback method - and returns the callback response. -- ``GetOidcAccessTokenAsync()``: This method is an asynchronous version of the previous - method. - -The following code is an example implementation of the ``IOidcCallback`` interface. -In this example, the methods retrieve an OIDC token from a file named ``"access-token.dat"`` -in the local file system. - -.. code-block:: csharp - - public class MyCallback : IOidcCallback - { - public OidcAccessToken GetOidcAccessToken( - OidcCallbackParameters parameters, - CancellationToken cancellationToken) - { - var accessToken = File.ReadAllText("access-token.dat"); - return new(accessToken, expiresIn: null); - } - - public async Task GetOidcAccessTokenAsync( - OidcCallbackParameters parameters, - CancellationToken cancellationToken) - { - var accessToken = await File.ReadAllTextAsync( - "access-token.dat", - cancellationToken) - .ConfigureAwait(false); - return new(accessToken, expiresIn: null); - } - } - -After you define a class that contains your custom callback methods, call the -``MongoCredential.CreateOidcCredential()`` method and pass in a new instance of your -class. Store the result of this method call in the ``Credential`` property of your -``MongoClientSettings`` object, as shown in the following code example: - -.. code-block:: csharp - - var mongoClientSettings = MongoClientSettings.FromConnectionString("mongodb://[:port]"); - mongoClientSettings.Credential = MongoCredential.CreateOidcCredential(new MyCallback()); - var client = new MongoClient(mongoClientSettings); - -API Documentation ------------------ - -To learn more about any of the methods or types discussed in this -guide, see the following API Documentation: - -- `MongoCredential() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoCredential.html>`__ -- `MongoClient() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClient.html>`__ -- `MongoClientSettings <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.html>`__ -- `CreateGssapiCredential() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoCredential.CreateGssapiCredential.html>`__ -- `CreatePlainCredential() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoCredential.CreatePlainCredential.html>`__ -- `IOidcCallback <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Authentication.Oidc.IOidcCallback.html>`__ diff --git a/source/includes/comma-auth-options.rst b/source/includes/comma-auth-options.rst new file mode 100644 index 00000000..a5ac6ac4 --- /dev/null +++ b/source/includes/comma-auth-options.rst @@ -0,0 +1,6 @@ +.. note:: + + You cannot pass values containing the comma (``,``) character to the + ``authMechanismProperties`` connection string parameter. + You must specify values that contain commas in a ``MongoCredential`` object, + as demonstrated in the :guilabel:`MongoCredential` tab. \ No newline at end of file diff --git a/source/includes/troubleshooting/x509.rst b/source/includes/troubleshooting/x509.rst new file mode 100644 index 00000000..bb0127bc --- /dev/null +++ b/source/includes/troubleshooting/x509.rst @@ -0,0 +1,18 @@ +If you are using Windows as your operating system, you might encounter an issue in which the +{+driver-short+} is unable to locate an ``X.509`` authentication certificate in memory. +This error displays the following error message: + +.. code-block:: none + :copyable: false + + No credentials are available in the security package + +To resolve this issue, add the following code to your application. This code generates +any ``X.509`` certificates required by your application and stores them to disk: + +.. code-block:: csharp + + using (X509Certificate2 certWithKey = certOnly.CopyWithPrivateKey(key)) + { + return new X509Certificate2(certWithKey.Export(X509ContentType.Pkcs12)); + } \ No newline at end of file From 2dce924af6df59087337f4760687e97333b6f9a6 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Wed, 27 Nov 2024 09:37:13 -0600 Subject: [PATCH 2/3] autobuilder From a249c4156dc7ac62cbbae8421ddd6a22385273b7 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Wed, 27 Nov 2024 09:50:26 -0600 Subject: [PATCH 3/3] remove odata --- source/fundamentals.txt | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/source/fundamentals.txt b/source/fundamentals.txt index 78c0d727..26225a58 100644 --- a/source/fundamentals.txt +++ b/source/fundamentals.txt @@ -30,7 +30,6 @@ Fundamentals In-Use Encryption Search Geospatially Replica Set Operations - OData - :ref:`Connecting to MongoDB ` - :ref:`csharp-db-coll` @@ -50,5 +49,4 @@ Fundamentals - :ref:`csharp-time-series` - :ref:`Encrypt Fields ` - :ref:`csharp-geo` -- :ref:`csharp-read-write-config` -- :ref:`csharp-odata` +- :ref:`csharp-read-write-config` \ No newline at end of file