diff --git a/snooty.toml b/snooty.toml index de16c44e..e23ffda8 100644 --- a/snooty.toml +++ b/snooty.toml @@ -10,6 +10,7 @@ toc_landing_pages = [ "/aggregation", "/aggregation/aggregation-tutorials", "/security", + "/security/authentication", "/aggregation-tutorials", "/data-formats", ] diff --git a/source/includes/authentication/azure-envs-mongoclient.py b/source/includes/authentication/azure-envs-mongoclient.py index 20b63f4d..380e90ed 100644 --- a/source/includes/authentication/azure-envs-mongoclient.py +++ b/source/includes/authentication/azure-envs-mongoclient.py @@ -4,7 +4,7 @@ # define callback, properties, and MongoClient audience = "" -client_id = "" +client_id = "" class MyCallback(OIDCCallback): def fetch(self, context: OIDCCallbackContext) -> OIDCCallbackResult: credential = DefaultAzureCredential(managed_identity_client_id=client_id) @@ -12,7 +12,7 @@ def fetch(self, context: OIDCCallbackContext) -> OIDCCallbackResult: return OIDCCallbackResult(access_token=token) properties = {"OIDC_CALLBACK": MyCallback()} client = MongoClient( - "mongodb://:", + "mongodb[+srv]://:", authMechanism="MONGODB-OIDC", authMechanismProperties=properties ) \ No newline at end of file diff --git a/source/includes/authentication/azure-imds-connection-string.py b/source/includes/authentication/azure-imds-connection-string.py index e4c41621..cf9260ee 100644 --- a/source/includes/authentication/azure-imds-connection-string.py +++ b/source/includes/authentication/azure-imds-connection-string.py @@ -1,8 +1,8 @@ from pymongo import MongoClient # define URI and MongoClient -uri = ("mongodb://:/?" - "username=" +uri = ("mongodb[+srv]://:/?" + "username=" "&authMechanism=MONGODB-OIDC" "&authMechanismProperties=ENVIRONMENT:azure,TOKEN_RESOURCE:") client = MongoClient(uri) \ No newline at end of file diff --git a/source/includes/authentication/azure-imds-mongoclient.py b/source/includes/authentication/azure-imds-mongoclient.py index c6c2035b..58c5585f 100644 --- a/source/includes/authentication/azure-imds-mongoclient.py +++ b/source/includes/authentication/azure-imds-mongoclient.py @@ -3,8 +3,8 @@ # define properties and MongoClient properties = {"ENVIRONMENT": "azure", "TOKEN_RESOURCE": ""} client = MongoClient( - "mongodb://:", - username="", + "mongodb[+srv]://:", + username="", authMechanism="MONGODB-OIDC", authMechanismProperties=properties ) \ No newline at end of file diff --git a/source/includes/authentication/gcp-gke-mongoclient.py b/source/includes/authentication/gcp-gke-mongoclient.py index 1f0b3a3f..5f2320e5 100644 --- a/source/includes/authentication/gcp-gke-mongoclient.py +++ b/source/includes/authentication/gcp-gke-mongoclient.py @@ -9,7 +9,7 @@ def fetch(self, context: OIDCCallbackContext) -> OIDCCallbackResult: return OIDCCallbackResult(access_token=token) properties = {"OIDC_CALLBACK": MyCallback()} client = MongoClient( - "mongodb://:", + "mongodb[+srv]://:", authMechanism="MONGODB-OIDC", authMechanismProperties=properties ) \ No newline at end of file diff --git a/source/includes/authentication/gcp-imds-connection-string.py b/source/includes/authentication/gcp-imds-connection-string.py index 40da22fd..c63d46e3 100644 --- a/source/includes/authentication/gcp-imds-connection-string.py +++ b/source/includes/authentication/gcp-imds-connection-string.py @@ -1,7 +1,7 @@ from pymongo import MongoClient # define URI and MongoClient -uri = ("mongodb://:/?" +uri = ("mongodb[+srv]://:/?" "&authMechanism=MONGODB-OIDC" "&authMechanismProperties=ENVIRONMENT:gcp,TOKEN_RESOURCE:") client = MongoClient(uri) \ No newline at end of file diff --git a/source/includes/authentication/gcp-imds-mongoclient.py b/source/includes/authentication/gcp-imds-mongoclient.py index e42a6f3f..fe4cb97e 100644 --- a/source/includes/authentication/gcp-imds-mongoclient.py +++ b/source/includes/authentication/gcp-imds-mongoclient.py @@ -3,7 +3,7 @@ # define properties and MongoClient properties = {"ENVIRONMENT": "gcp", "TOKEN_RESOURCE": ""} client = MongoClient( - "mongodb://:", + "mongodb[+srv]://:", authMechanism="MONGODB-OIDC", authMechanismProperties=properties ) \ No newline at end of file diff --git a/source/includes/authentication/percent-encoding.rst b/source/includes/authentication/percent-encoding.rst new file mode 100644 index 00000000..7a8c0049 --- /dev/null +++ b/source/includes/authentication/percent-encoding.rst @@ -0,0 +1,10 @@ +.. important:: Percent-Encoding + + You must :wikipedia:`percent-encode ` a username and password before + you include them in a MongoDB URI. The ``quote_plus()`` method, available in the + `urllib.parse `__ + module, is one way to perform this task. For example, calling ``quote_plus("and / or")`` + returns the string ``and+%2F+or``. + + Don't percent-encode the username or password when passing them as arguments to + ``MongoClient``. \ No newline at end of file diff --git a/source/security.txt b/source/security.txt index 80748fcd..01079131 100644 --- a/source/security.txt +++ b/source/security.txt @@ -23,7 +23,6 @@ Secure Your Data :maxdepth: 1 Authentication - Enterprise Authentication In-Use Encryption Overview diff --git a/source/security/authentication.txt b/source/security/authentication.txt index 9221b0cd..5092d399 100644 --- a/source/security/authentication.txt +++ b/source/security/authentication.txt @@ -1,5 +1,8 @@ +.. _pymongo-authentication-mechanisms: .. _pymongo-auth: +.. _pymongo-enterprise-auth: +========================= Authentication Mechanisms ========================= @@ -12,533 +15,70 @@ Authentication Mechanisms .. facet:: :name: genre :values: reference - -.. meta:: - :keywords: authorize, boto, ecs, aws - -Overview --------- - -This guide describes the mechanisms you can use in {+driver-short+} to authenticate -users. - -.. important:: Percent-Encoding - - You must :wikipedia:`percent-encode ` a username and password before - you include them in a MongoDB URI. The ``quote_plus()`` method, available in the - `urllib.parse `__ - module, is one way to perform this task. For example, calling ``quote_plus("and / or")`` - returns the string ``and+%2F+or``. - - Don't percent-encode the username or password when passing them as arguments to - ``MongoClient``. - -.. _pymongo-scram-sha-256: - -SCRAM-SHA-256 -------------- - -SCRAM-SHA-256, as defined by `RFC 7677 `__, -is the default authentication mechanism on MongoDB deployments -running MongoDB v4.0 or later. - -To authenticate with this mechanism, set the following connection options: - -- ``db_username``: The username to authenticate. Percent-encode this value before including - it in a connection URI. -- ``db_password``: The password to authenticate. Percent-encode this value before including - it in a connection URI. -- ``authSource``: The MongoDB database to authenticate against. By default, - {+driver-short+} authenticates against the database in the connection - URI, if you include one. If you don't, it authenticates against the ``admin`` database. -- ``authMechanism``: Set to ``SCRAM-SHA-256``. - -You can set these options in two ways: by passing arguments to the -``MongoClient`` constructor or through parameters in your connection string. - -.. tabs:: - - .. tab:: MongoClient - :tabid: mongoclient - - .. code-block:: python - - client = pymongo.MongoClient("mongodb://:", - username="", - password="", - authSource="", - authMechanism="SCRAM-SHA-256") - - .. tab:: Connection String - :tabid: connectionstring - - .. code-block:: python - - uri = ("mongodb://:" - "@:/?" - "authSource=" - "&authMechanism=SCRAM-SHA-256") - client = pymongo.MongoClient(uri) - -.. _pymongo-scram-sha-1: - -SCRAM-SHA-1 ------------ - -SCRAM-SHA-1, as defined by `RFC 5802 `__, -is the default authentication mechanism on MongoDB deployments -running MongoDB v3.6. - -To authenticate with this mechanism, set the following connection options: - -- ``db_username``: The username to authenticate. Percent-encode this value before including - it in a connection URI. -- ``db_password``: The password to authenticate. Percent-encode this value before including - it in a connection URI. -- ``authSource``: The MongoDB database to authenticate against. By default, - {+driver-short+} authenticates against the ``admin`` database. -- ``authMechanism``: Set to ``"SCRAM-SHA-1"``. - -You can set these options in two ways: by passing arguments to the -``MongoClient`` constructor or through parameters in your connection string. - -.. tabs:: - - .. tab:: MongoClient - :tabid: mongoclient - - .. code-block:: python - - client = pymongo.MongoClient("mongodb://:", - username="", - password="", - authSource="", - authMechanism="SCRAM-SHA-1") - - .. tab:: Connection String - :tabid: connectionstring - - .. code-block:: python - - uri = ("mongodb://:" - "@:/?" - "authSource=" - "&authMechanism=SCRAM-SHA-1") - client = pymongo.MongoClient(uri) - -.. _pymongo-mongodb-x509: - -MONGODB-X509 ------------- - -If you enable TLS, during the TLS handshake, {+driver-short+} can present an X.509 -client certificate to MongoDB to prove its identity. The MONGODB-X509 authentication -mechanism uses this certificate to authenticate the client. - -To authenticate with this mechanism, set the following connection options: - -- ``tls``: Set to ``True``. -- ``tlsCertificateKeyFile``: The file path of the ``.pem`` file that contains your - client certificate and private key. -- ``authMechanism``: Set to ``"MONGODB-X509"``. - -You can set these options in two ways: by passing arguments to the -``MongoClient`` constructor or through parameters in your connection string. - -.. tabs:: - - .. tab:: MongoClient - :tabid: mongoclient - - .. code-block:: python - - client = pymongo.MongoClient("mongodb://:", - tls=True, - tlsCertificateKeyFile="/path/to/client.pem", - authMechanism="MONGODB-X509") - - .. tab:: Connection String - :tabid: connectionstring - - .. code-block:: python - - uri = ("mongodb://:/?" - "tls=true" - "&tlsCertificateKeyFile=path/to/client.pem" - "&authMechanism=MONGODB-X509") - client = pymongo.MongoClient(uri) - -.. _pymongo-mongodb-aws: - -MONGODB-AWS ------------ - -.. important:: - - The MONGODB-AWS authentication mechanism requires MongoDB v4.4 or later. - -The MONGODB-AWS authentication mechanism uses AWS IAM (Amazon Web Services Identity and -Access Management) or AWS Lambda credentials to authenticate your application. -To use MONGODB-AWS for authentication, you must install {+driver-short+} with the -``aws`` option, as shown in the following example: - -.. code-block:: sh - - python -m pip install pymongo[aws] - -{+driver-short+} uses Boto3, the AWS SDK for Python, to handle credentials. Boto3 -tries to retrieve AWS credentials from the following sources, in the order listed: - -1. Named arguments passed to the ``MongoClient`` constructor or parameters in the - connection URI -#. Environment variables -#. Shared credentials file -#. AWS config file -#. ``AssumeRole`` request to the AWS Security Token Service (STS) -#. ``AssumeRoleWithWebIdentity`` request to the AWS STS -#. Instance metadata service on an Amazon EC2 instance with an IAM role configured - -The following sections describe how to use {+driver-short+} to retrieve credentials from -these sources and use them to authenticate your application. - -.. _pymongo-mongodb-aws-credentials: - -``MongoClient`` Credentials -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -First, {+driver-short+} checks whether you passed AWS credentials -to the ``MongoClient`` constructor, either as a named argument or as part of the -connection URI. To pass your credentials to ``MongoClient``, -set the following connection options: - -- ``username``: The AWS IAM access key ID to authenticate. Percent-encode this value - before including it in a connection URI. -- ``password``: The AWS IAM secret access key. Percent-encode this value before including - it in a connection URI. -- ``authMechanism``: Set to ``"MONGODB-AWS"``. - -You can set these options in two ways: by passing arguments to the -``MongoClient`` constructor or through parameters in your connection string. - -.. tabs:: - - .. tab:: MongoClient - :tabid: mongoclient - - .. code-block:: python - - client = pymongo.MongoClient("mongodb://@:", - username="", - password="", - authMechanism="MONGODB-AWS") - - .. tab:: Connection String - :tabid: connectionstring - - .. code-block:: python - - uri = ("mongodb://:" - "" - "@:/?" - "&authMechanism=MONGODB-AWS") - client = pymongo.MongoClient(uri) - -.. _pymongo-mongodb-aws-env-vars: - -Environment Variables -~~~~~~~~~~~~~~~~~~~~~ - -If you don't provide a username and password when you construct your ``MongoClient`` -object, {+driver-short+} tries to retrieve AWS credentials from the following -environment variables: - -- ``AWS_ACCESS_KEY_ID`` -- ``AWS_SECRET_ACCESS_KEY`` -- ``AWS_SESSION_TOKEN`` - -To use these environment variables to authenticate your application, first set them to the -AWS IAM values needed for authentication, as shown in the following code -example: - -.. code-block:: sh - - export AWS_ACCESS_KEY_ID= - export AWS_SECRET_ACCESS_KEY= - export AWS_SESSION_TOKEN= - -.. important:: - - Don't percent-encode the values in these environment variables. - -After you set these environment variables, set the ``authMechanism`` -connection option to ``"MONGODB-AWS"``. -You can set this option in two ways: by passing an argument to the -``MongoClient`` constructor or through a parameter in your connection string. -.. tabs:: - - .. tab:: MongoClient - :tabid: mongoclient - - .. code-block:: python - - client = pymongo.MongoClient("mongodb://:", - authMechanism="MONGODB-AWS") - - .. tab:: Connection String - :tabid: connectionstring - - .. code-block:: python - - uri = "mongodb://:/?&authMechanism=MONGODB-AWS" - client = pymongo.MongoClient(uri) - -.. tip:: AWS Lambda - - AWS Lambda runtimes can automatically set these environment variables during - initialization. For more information about using environment variables in an AWS Lambda - environment, see - `Using Lambda environment variables `__ - in the AWS documentation. - -.. _pymongo-mongodb-aws-creds-file: - -Shared Credentials File -~~~~~~~~~~~~~~~~~~~~~~~ - -If {+driver-short+} doesn't find AWS credentials in the preceding environment variables, -it tries to read them from a shared credentials file. - -To use a shared credentials file to authenticate your application, ensure that the -file exists in your environment and is configured correctly. To learn how to create -a shared credentials file, see -`Credentials `__ -in the Boto3 documentation and `Configuration `__ -in the AWS documentation. - -After you create the shared credentials file, set the ``authMechanism`` -connection option to ``"MONGODB-AWS"``. -You can set this option in two ways: by passing an argument to the -``MongoClient`` constructor or through a parameter in your connection string. - -.. tabs:: - - .. tab:: MongoClient - :tabid: mongoclient - - .. code-block:: python - - client = pymongo.MongoClient("mongodb://:", - authMechanism="MONGODB-AWS") - - .. tab:: Connection String - :tabid: connectionstring - - .. code-block:: python - - uri = "mongodb://:/?&authMechanism=MONGODB-AWS" - client = pymongo.MongoClient(uri) - -.. tip:: - - To prevent {+driver-short+} from using a shared credentials file for authentication, - perform one of the following actions: - - - Set the ``AWS_SHARED_CREDENTIALS_FILE`` environment variable to ``""`` in your terminal. - - Add ``os.environ["AWS_SHARED_CREDENTIALS_FILE"] = ""`` to your script or - application. - - Create an AWS profile specifically for your MongoDB credentials. Set the ``AWS_PROFILE`` - environment variable to the name of the profile you created. - -.. _pymongo-mongodb-aws-config-file: - -AWS Config File -~~~~~~~~~~~~~~~ - -If {+driver-short+} doesn't find credentials in the shared credentials file, it tries to read -them from an AWS config file. - -To use an AWS config file to authenticate your application, ensure that the -file exists in your environment and is configured correctly. To learn how to create -an AWS config file, see -`Credentials `__ -in the Boto3 documentation and `Configuration `__ -in the AWS documentation. - -After you create the config file, set the ``authMechanism`` -connection option to ``"MONGODB-AWS"``. -You can set this option in two ways: by passing an argument to the -``MongoClient`` constructor or through a parameter in your connection string. - -.. tabs:: - - .. tab:: MongoClient - :tabid: mongoclient - - .. code-block:: python - - client = pymongo.MongoClient("mongodb://:", - authMechanism="MONGODB-AWS") - - .. tab:: Connection String - :tabid: connectionstring - - .. code-block:: python - - uri = "mongodb://:/?&authMechanism=MONGODB-AWS" - client = pymongo.MongoClient(uri) - -.. _pymongo-mongodb-aws-assume-role: - -AssumeRole Request -~~~~~~~~~~~~~~~~~~ - -Instead of storing AWS credentials in your AWS config file, you can instruct -{+driver-short+} to make an ``AssumeRole`` request to an AWS STS endpoint. This request -returns temporary credentials that your application can use for authentication. - -To authenticate with temporary AWS IAM credentials returned by an ``AssumeRole`` request, -ensure that the AWS config file exists in your environment and is configured correctly. -To learn how to create and configure -an AWS config file, see -`Credentials `__ -in the Boto3 documentation and `Configuration `__ -in the AWS documentation. - -After you create the config file, set the following connection options: - -- ``username``: The AWS IAM access key ID to authenticate returned by the ``AssumeRole`` - request. Percent-encode this value before including it in a connection URI. -- ``password``: The AWS IAM secret access key returned by the ``AssumeRole`` request. - Percent-encode this value before including it in a connection URI.. -- ``authMechanismProperties``: Set to ``AWS_SESSION_TOKEN:`` and the - AWS session token returned by the ``AssumeRole`` request. -- ``authMechanism``: Set to ``"MONGODB-AWS"``. - -You can set these options in two ways: by passing arguments to the -``MongoClient`` constructor or through parameters in your connection string. - -.. include:: /includes/authentication/auth-properties-commas.rst - -.. tabs:: - - .. tab:: MongoClient - :tabid: mongoclient - - .. code-block:: python - - client = pymongo.MongoClient("mongodb://@:", - username="", - password="", - authMechanismProperties="AWS_SESSION_TOKEN:", - authMechanism="MONGODB-AWS") - - .. tab:: Connection String - :tabid: connectionstring - - .. code-block:: python +.. meta:: + :keywords: community, security - uri = ("mongodb://:" - "" - "@:/?" - "authMechanismProperties=AWS_SESSION_TOKEN:" - "&authMechanism=MONGODB-AWS") - client = pymongo.MongoClient(uri) +.. toctree:: + :caption: Authentication -For more information about using the ``AssumeRole`` request to authenticate your -application, see the following AWS documentation: - -- `Temporary AWS IAM credentials `__ -- `AWS Security Token Service `__ -- `Assume Role `__ + SCRAM + X.509 + AWS IAM + OIDC + LDAP (PLAIN) + Kerberos (GSSAPI) -.. _EKS Clusters: -.. _pymongo-mongodb-aws-oidc: +Overview +-------- -AssumeRoleWithWebIdentity -~~~~~~~~~~~~~~~~~~~~~~~~~ +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. -.. important:: +.. tip:: Connecting to MongoDB - Your application must use ``pymongo_auth_aws`` v1.1.0 or later for EKS support. - -If your application authenticates users for your EKS cluster from an OpenID Connect (OIDC) -identity provider, {+driver-short+} can make an ``AssumeRoleWithWebIdentity`` request -to exchange the OIDC token for temporary AWS credentials for your application. - -To authenticate with temporary AWS IAM credentials returned by an -``AssumeRoleWithWebIdentity`` request, ensure that the AWS config file exists in your -environment and is configured correctly. To learn how to create and configure -an AWS config file, see -`Credentials `__ -in the Boto3 documentation and `Configuration `__ -in the AWS documentation. - -After you configure your environment for an ``AssumeRoleWithWebIdentity`` request, -set the ``authMechanism`` connection option to ``"MONGODB-AWS"``. -You can set this option in two ways: by passing an argument to the -``MongoClient`` constructor or through a parameter in your connection string. - -.. tabs:: - - .. tab:: MongoClient - :tabid: mongoclient - - .. code-block:: python - - client = pymongo.MongoClient("mongodb://:", - authMechanism="MONGODB-AWS") - - .. tab:: Connection String - :tabid: connectionstring - - .. code-block:: python - - uri = "mongodb://:/?&authMechanism=MONGODB-AWS" - client = pymongo.MongoClient(uri) - -For more information about using an ``AssumeRoleWithWebIdentity`` request to -authenticate your application, see the following AWS documentation: - -- `Authenticating users for your cluster from an OpenID Connect identity provider `__ -- `AssumeRoleWithWebIdentity `__ - -.. _pymongo-mongodb-aws-ec: - -ECS Container or EC2 Instance -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If your application runs in an Amazon Elastic Cloud Compute (EC2) instance in an -Elastic Container Service (ECS) container, {+driver-short+} can automatically retrieve -temporary AWS credentials from an ECS endpoint. - -To use temporary credentials from within an EC2 instance, set the ``authMechanism`` -connection option to ``"MONGODB-AWS"``. -You can set this option in two ways: by passing an argument to the -``MongoClient`` constructor or through a parameter in your connection string. - -.. tabs:: - - .. tab:: MongoClient - :tabid: mongoclient - - .. code-block:: python - - client = pymongo.MongoClient("mongodb://:", - authMechanism="MONGODB-AWS") - - .. tab:: Connection String - :tabid: connectionstring - - .. code-block:: python - - uri = "mongodb://:/?&authMechanism=MONGODB-AWS" - client = pymongo.MongoClient(uri) - -API Documentation ------------------ - -To learn more about authenticating your application in {+driver-short+}, -see the following API documentation: - -- `MongoClient <{+api-root+}pymongo/mongo_client.html#pymongo.mongo_client.MongoClient>`__ \ No newline at end of file + To learn how to establish a connection to your MongoDB deployment, see + :ref:`pymongo-get-started`. + +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 + :widths: 40 20 20 20 + + * - 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 \ No newline at end of file diff --git a/source/security/authentication/aws-iam.txt b/source/security/authentication/aws-iam.txt new file mode 100644 index 00000000..e6dc0f07 --- /dev/null +++ b/source/security/authentication/aws-iam.txt @@ -0,0 +1,413 @@ +.. _pymongo-mongodb-aws: + +================================== +AWS Identity and Access Management +================================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 3 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: boto, amazon web services, code example, authorize + +Overview +-------- + +The ``MONGODB-AWS`` authentication mechanism uses Amazon Web Services +Identity and Access Management (AWS IAM) or AWS Lambda 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. + +.. include:: /includes/authentication/percent-encoding.rst + +Using AWS IAM Authentication in Your Application +------------------------------------------------ + +To use AWS IAM authentication, you must install {+driver-short+} with the +``aws`` option, as shown in the following example: + +.. code-block:: sh + + python -m pip install pymongo[aws] + +{+driver-short+} uses Boto3, the AWS SDK for Python, to handle credentials. Boto3 +tries to retrieve AWS credentials from the following sources, in the order listed: + +1. Named arguments passed to the ``MongoClient`` constructor or parameters in the + connection string +#. Environment variables +#. Shared credentials file +#. AWS config file +#. ``AssumeRole`` request to the AWS Security Token Service (STS) +#. ``AssumeRoleWithWebIdentity`` request to the AWS STS +#. Instance metadata service on an Amazon EC2 instance with an IAM role configured + +The following sections describe how to use {+driver-short+} to retrieve credentials from +these sources and use them to authenticate your application. + +.. _pymongo-mongodb-aws-credentials: + +``MongoClient`` Credentials +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +First, {+driver-short+} checks whether you passed AWS credentials +to the ``MongoClient`` constructor, either as a named argument or as part of the +connection string. To pass your credentials to ``MongoClient``, +set the following connection options: + +- ``username``: The AWS IAM access key ID to authenticate. Percent-encode this value + before including it in a connection string. +- ``password``: The AWS IAM secret access key. Percent-encode this value before including + it in a connection string. +- ``authMechanism``: Set to ``"MONGODB-AWS"``. + +You can set these options in two ways: by passing arguments to the +``MongoClient`` constructor or through parameters in your connection string. + +.. tabs:: + + .. tab:: MongoClient + :tabid: mongoclient + + .. code-block:: python + + client = pymongo.MongoClient("mongodb+srv://", + username="", + password="", + authMechanism="MONGODB-AWS") + + .. tab:: Connection String + :tabid: connectionstring + + .. code-block:: python + + uri = ("mongodb+srv://:" + "" + "@/?" + "&authMechanism=MONGODB-AWS") + client = pymongo.MongoClient(uri) + +.. _pymongo-mongodb-aws-env-vars: + +Environment Variables +~~~~~~~~~~~~~~~~~~~~~ + +If you don't provide a username and password when you construct your ``MongoClient`` +object, {+driver-short+} tries to retrieve AWS credentials from the following +environment variables: + +- ``AWS_ACCESS_KEY_ID`` +- ``AWS_SECRET_ACCESS_KEY`` +- ``AWS_SESSION_TOKEN`` + +To use these environment variables to authenticate your application, first set them to the +AWS IAM values needed for authentication, as shown in the following code +example: + +.. code-block:: sh + + export AWS_ACCESS_KEY_ID= + export AWS_SECRET_ACCESS_KEY= + export AWS_SESSION_TOKEN= + +.. important:: + + Don't percent-encode the values in these environment variables. + +After you set these environment variables, set the ``authMechanism`` +connection option to ``"MONGODB-AWS"``. +You can set this option in two ways: by passing an argument to the +``MongoClient`` constructor or through a parameter in your connection string. + +.. tabs:: + + .. tab:: MongoClient + :tabid: mongoclient + + .. code-block:: python + + client = pymongo.MongoClient("mongodb+srv://", + authMechanism="MONGODB-AWS") + + .. tab:: Connection String + :tabid: connectionstring + + .. code-block:: python + + uri = "mongodb+srv:///?&authMechanism=MONGODB-AWS" + client = pymongo.MongoClient(uri) + +.. tip:: AWS Lambda + + AWS Lambda runtimes can automatically set these environment variables during + initialization. For more information about using environment variables in an AWS Lambda + environment, see + `Using Lambda environment variables `__ + in the AWS documentation. + +.. _pymongo-mongodb-aws-creds-file: + +Shared Credentials File +~~~~~~~~~~~~~~~~~~~~~~~ + +If {+driver-short+} doesn't find AWS credentials in the preceding environment variables, +it tries to read them from a shared credentials file. + +To use a shared credentials file to authenticate your application, ensure that the +file exists in your environment and is configured correctly. To learn how to create +a shared credentials file, see +`Credentials `__ +in the Boto3 documentation and `Configuration `__ +in the AWS documentation. + +After you create the shared credentials file, set the ``authMechanism`` +connection option to ``"MONGODB-AWS"``. +You can set this option in two ways: by passing an argument to the +``MongoClient`` constructor or through a parameter in your connection string. + +.. tabs:: + + .. tab:: MongoClient + :tabid: mongoclient + + .. code-block:: python + + client = pymongo.MongoClient("mongodb+srv://", + authMechanism="MONGODB-AWS") + + .. tab:: Connection String + :tabid: connectionstring + + .. code-block:: python + + uri = "mongodb+srv:///?&authMechanism=MONGODB-AWS" + client = pymongo.MongoClient(uri) + +.. tip:: + + To prevent {+driver-short+} from using a shared credentials file for authentication, + perform one of the following actions: + + - Set the ``AWS_SHARED_CREDENTIALS_FILE`` environment variable to ``""`` in your terminal. + - Add ``os.environ["AWS_SHARED_CREDENTIALS_FILE"] = ""`` to your script or + application. + - Create an AWS profile specifically for your MongoDB credentials. Set the ``AWS_PROFILE`` + environment variable to the name of the profile you created. + +.. _pymongo-mongodb-aws-config-file: + +AWS Config File +~~~~~~~~~~~~~~~ + +If {+driver-short+} doesn't find credentials in the shared credentials file, it tries to read +them from an AWS config file. + +To use an AWS config file to authenticate your application, ensure that the +file exists in your environment and is configured correctly. To learn how to create +an AWS config file, see +`Credentials `__ +in the Boto3 documentation and +`Configuration `__ +in the AWS documentation. + +After you create the config file, set the ``authMechanism`` +connection option to ``"MONGODB-AWS"``. +You can set this option in two ways: by passing an argument to the +``MongoClient`` constructor or through a parameter in your connection string. + +.. tabs:: + + .. tab:: MongoClient + :tabid: mongoclient + + .. code-block:: python + + client = pymongo.MongoClient("mongodb+srv://", + authMechanism="MONGODB-AWS") + + .. tab:: Connection String + :tabid: connectionstring + + .. code-block:: python + + uri = "mongodb+srv:///?&authMechanism=MONGODB-AWS" + client = pymongo.MongoClient(uri) + +.. _pymongo-mongodb-aws-assume-role: + +AssumeRole Request +~~~~~~~~~~~~~~~~~~ + +Instead of storing AWS credentials in your AWS config file, you can instruct +{+driver-short+} to make an ``AssumeRole`` request to an AWS STS endpoint. This request +returns temporary credentials that your application can use for authentication. + +To authenticate with temporary AWS IAM credentials returned by an ``AssumeRole`` request, +ensure that the AWS config file exists in your environment and is configured correctly. +To learn how to create and configure +an AWS config file, see +`Credentials `__ +in the Boto3 documentation and `Configuration `__ +in the AWS documentation. + +After you create the config file, set the following connection options: + +- ``username``: The AWS IAM access key ID to authenticate returned by the ``AssumeRole`` + request. Percent-encode this value before including it in a connection string. +- ``password``: The AWS IAM secret access key returned by the ``AssumeRole`` request. + Percent-encode this value before including it in a connection string. +- ``authMechanismProperties``: Set to ``AWS_SESSION_TOKEN:`` and the + AWS session token returned by the ``AssumeRole`` request. +- ``authMechanism``: Set to ``"MONGODB-AWS"``. + +You can set these options in two ways: by passing arguments to the +``MongoClient`` constructor or through parameters in your connection string. + +.. include:: /includes/authentication/auth-properties-commas.rst + +.. tabs:: + + .. tab:: MongoClient + :tabid: mongoclient + + .. code-block:: python + + client = pymongo.MongoClient("mongodb+srv://@", + username="", + password="", + authMechanismProperties="AWS_SESSION_TOKEN:", + authMechanism="MONGODB-AWS") + + .. tab:: Connection String + :tabid: connectionstring + + .. code-block:: python + + uri = ("mongodb+srv://:" + "" + "@/?" + "authMechanismProperties=AWS_SESSION_TOKEN:" + "&authMechanism=MONGODB-AWS") + client = pymongo.MongoClient(uri) + +For more information about using the ``AssumeRole`` request to authenticate your +application, see the following AWS documentation: + +- `Temporary AWS IAM credentials `__ +- `AWS Security Token Service `__ +- `Assume Role `__ + +.. _EKS Clusters: +.. _pymongo-mongodb-aws-oidc: + +AssumeRoleWithWebIdentity +~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. important:: + + Your application must use ``pymongo_auth_aws`` v1.1.0 or later for EKS support. + +If your application authenticates users for your EKS cluster from an OpenID Connect (OIDC) +identity provider, {+driver-short+} can make an ``AssumeRoleWithWebIdentity`` request +to exchange the OIDC token for temporary AWS credentials for your application. + +To authenticate with temporary AWS IAM credentials returned by an +``AssumeRoleWithWebIdentity`` request, ensure that the AWS config file exists in your +environment and is configured correctly. To learn how to create and configure +an AWS config file, see +`Credentials `__ +in the Boto3 documentation and `Configuration `__ +in the AWS documentation. + +After you configure your environment for an ``AssumeRoleWithWebIdentity`` request, +set the ``authMechanism`` connection option to ``"MONGODB-AWS"``. +You can set this option in two ways: by passing an argument to the +``MongoClient`` constructor or through a parameter in your connection string. + +.. tabs:: + + .. tab:: MongoClient + :tabid: mongoclient + + .. code-block:: python + + client = pymongo.MongoClient("mongodb+srv://", + authMechanism="MONGODB-AWS") + + .. tab:: Connection String + :tabid: connectionstring + + .. code-block:: python + + uri = "mongodb+srv:///?&authMechanism=MONGODB-AWS" + client = pymongo.MongoClient(uri) + +For more information about using an ``AssumeRoleWithWebIdentity`` request to +authenticate your application, see the following AWS documentation: + +- `Authenticating users for your cluster from an OpenID Connect identity provider `__ +- `AssumeRoleWithWebIdentity `__ + +.. _pymongo-mongodb-aws-ec: + +ECS Container or EC2 Instance +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your application runs in an Amazon Elastic Cloud Compute (EC2) instance in an +Elastic Container Service (ECS) container, {+driver-short+} can automatically retrieve +temporary AWS credentials from an ECS endpoint. + +To use temporary credentials from within an EC2 instance, set the ``authMechanism`` +connection option to ``"MONGODB-AWS"``. +You can set this option in two ways: by passing an argument to the +``MongoClient`` constructor or through a parameter in your connection string. + +.. tabs:: + + .. tab:: MongoClient + :tabid: mongoclient + + .. code-block:: python + + client = pymongo.MongoClient("mongodb+srv://", + authMechanism="MONGODB-AWS") + + .. tab:: Connection String + :tabid: connectionstring + + .. code-block:: python + + uri = "mongodb+srv:///?&authMechanism=MONGODB-AWS" + client = pymongo.MongoClient(uri) + +API Documentation +----------------- + +To learn more about authenticating your application in {+driver-short+}, +see the following API documentation: + +- `MongoClient <{+api-root+}pymongo/mongo_client.html#pymongo.mongo_client.MongoClient>`__ \ No newline at end of file diff --git a/source/security/authentication/kerberos.txt b/source/security/authentication/kerberos.txt new file mode 100644 index 00000000..9cc2fd87 --- /dev/null +++ b/source/security/authentication/kerberos.txt @@ -0,0 +1,174 @@ +.. _pymongo-kerberos: + +================= +Kerberos (GSSAPI) +================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: authorization, 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. + +.. include:: /includes/authentication/percent-encoding.rst + +Using GSSAPI Authentication in Your Application +----------------------------------------------- + +Select the tab that corresponds to your operating system to learn how +to use Kerberos to authenticate. + +.. tabs:: + + .. tab:: Unix + :tabid: unix + + First, use pip or easy_install to install the Python + `kerberos `__ or + `pykerberos `__ module. + + After installing one of these modules, run the ``kinit`` command to obtain and cache + an initial ticket-granting ticket. The following example uses the + ``knit`` command to obtain a ticket-granting ticket for the principal + ``mongodbuser@EXAMPLE.COM``. It then uses the ``klist`` + command to display the principal and ticket in the credentials cache. + + .. code-block:: sh + :copyable: false + + $ kinit mongodbuser@EXAMPLE.COM + mongodbuser@EXAMPLE.COM's Password: + $ klist + Credentials cache: FILE:/tmp/krb5cc_1000 + Principal: mongodbuser@EXAMPLE.COM + + Issued Expires Principal + Feb 9 13:48:51 2013 Feb 9 23:48:51 2013 krbtgt/mongodbuser@EXAMPLE.COM + + After you obtain a ticket-granting ticket, set the following connection options: + + - ``username``: The Kerbos principal to authenticate. Percent-encode this value + before including it in a connection URI. + - ``authMechanism``: Set to ``"GSSAPI"``. + - ``authMechanismProperties``: Optional. By default, MongoDB uses ``mongodb`` as + the authentication service name. To specify a different service name, set + this option to ``"SERVICE_NAME:"``. + + You can set these options in two ways: by passing arguments to the + ``MongoClient`` constructor or through parameters in your connection + string. + + .. include:: /includes/authentication/auth-properties-commas.rst + + .. tabs:: + + .. tab:: MongoClient + :tabid: mongoclient + + .. code-block:: python + + client = pymongo.MongoClient("mongodb://:", + username="mongodbuser@EXAMPLE.COM", + authMechanism="GSSAPI", + authMechanismProperties="SERVICE_NAME:") + + .. tab:: Connection String + :tabid: connectionstring + + .. code-block:: python + + uri = ("mongodb://mongodbuser%40EXAMPLE.COM@:/?" + "&authMechanism=GSSAPI" + "&authMechanismProperties=SERVICE_NAME:") + client = pymongo.MongoClient(uri) + + .. tab:: Windows (SSPI) + :tabid: windows + + First, install the `winkerberos `__ module. + Then, set the following connection options: + + - ``username``: The Kerbos principal to authenticate. Percent-encode this value before including + it in a connection URI. + - ``authMechanism``: Set to ``"GSSAPI"``. + - ``password``: Optional. If the user to authenticate is different from the user + that owns the application process, set this option to the authenticating user's + password. + - ``authMechanismProperties``: Optional. This option includes multiple + authentication properties. To specify more than one of the following properties, + use a comma-delimited list. + + - ``SERVICE_NAME:`` By default, MongoDB uses ``mongodb`` as + the authentication service name. Use this option to specify a different service name. + - ``CANONICALIZE_HOST_NAME``: Whether to use the fully qualified domain name (FQDN) + of the MongoDB host for the server principal. + - ``SERVICE_REALM``: The service realm. Use this option when the user's + realm is different from the service's realm. + + You can set these options in two ways: by passing arguments to the + ``MongoClient`` constructor or through parameters in your connection string. + + .. tabs:: + + .. tab:: MongoClient + :tabid: mongoclient + + .. code-block:: python + + client = pymongo.MongoClient("mongodb://:", + username="mongodbuser@EXAMPLE.COM", + authMechanism="GSSAPI", + password="", + authMechanismProperties="SERVICE_NAME:, + CANONICALIZE_HOST_NAME:true, + SERVICE_REALM:") + + .. tab:: Connection String + :tabid: connectionstring + + .. code-block:: python + + uri = ("mongodb://mongodbuser%40EXAMPLE.COM:" + "@:/?" + "&authMechanism=GSSAPI" + "&authMechanismProperties=" + "SERVICE_NAME:," + "CANONICALIZE_HOST_NAME:true," + "SERVICE_REALM:") + client = pymongo.MongoClient(uri) + +API Documentation +----------------- + +To learn more about using enterprise authentication mechanisms with {+driver-short+}, +see the following API documentation: + +- `MongoClient <{+api-root+}pymongo/mongo_client.html#pymongo.mongo_client.MongoClient>`__ \ No newline at end of file diff --git a/source/security/authentication/ldap.txt b/source/security/authentication/ldap.txt new file mode 100644 index 00000000..3378e43e --- /dev/null +++ b/source/security/authentication/ldap.txt @@ -0,0 +1,101 @@ +.. _pymongo-ldap: +.. _pymongo-sasl: + +================= +LDAP (PLAIN SASL) +================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: authorization, code example + +Overview +-------- + +The PLAIN authentication mechanism allows you to use your Lightweight Directory Access +Protocol (LDAP) username and password to authenticate to MongoDB. +LDAP authentication uses the PLAIN Simple Authentication and Security Layer +(SASL) defined in `RFC-4616 `__. + +You can use this mechanism only when authenticating to MongoDB Atlas or MongoDB Enterprise +Advanced. + +.. important:: + + PLAIN SASL is a clear-text authentication mechanism. We strongly recommend that you + use TLS/SSL with certificate validation when using PLAIN SASL to authenticate to MongoDB. + + To learn more about how to enable TLS for your connection, see :ref:``. + +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. +- ````: 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. + +.. include:: /includes/authentication/percent-encoding.rst + +Using PLAIN Authentication in Your Application +---------------------------------------------- + +To use PLAIN to authenticate, set the ``authMechanism`` connection option to ``PLAIN``. +You can set this option in two ways: by passing an argument to the +``MongoClient`` constructor or through a parameter in your connection string. + +.. include:: /includes/authentication/auth-properties-commas.rst + +.. tabs:: + + .. tab:: MongoClient + :tabid: mongoclient + + .. code-block:: python + + client = pymongo.MongoClient("mongodb[+srv]://:", + username="", + password="", + authSource="", + authMechanism="PLAIN", + tls=True) + + .. tab:: Connection String + :tabid: connectionstring + + .. code-block:: python + + uri = ("mongodb[+srv]://:@:/?" + "authSource=" + "&authMechanism=PLAIN" + "&tls=true") + client = pymongo.MongoClient(uri) + +API Documentation +----------------- + +To learn more about using PLAIN SASL authentication mechanisms with {+driver-short+}, +see the following API documentation: + +- `MongoClient <{+api-root+}pymongo/mongo_client.html#pymongo.mongo_client.MongoClient>`__ \ No newline at end of file diff --git a/source/security/authentication/oidc.txt b/source/security/authentication/oidc.txt new file mode 100644 index 00000000..00a40cfc --- /dev/null +++ b/source/security/authentication/oidc.txt @@ -0,0 +1,296 @@ +.. _pymongo-mongodb-oidc: + +=================================== +OIDC (Workload Identity Federation) +=================================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: authorize, 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 value of the ``audience`` parameter configured on your MongoDB deployment. + +To use the code examples on this page, replace these placeholders with your own values. + +.. include:: /includes/authentication/percent-encoding.rst + +Using OIDC Authentication in Your Application +--------------------------------------------- + +The following sections describe how to use the MONGODB-OIDC authentication mechanism to +authenticate to various platforms. + +.. note:: + + Because Python's Standard Library doesn't support asynchronous HTTP requests, + all OIDC requests from {+driver-short+} are synchronous and block the ``asyncio`` loop. + +.. _pymongo-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 {+driver-short+}'s built-in Azure +support. + +You can configure OIDC for Azure IMDS in two ways: by passing arguments to the +``MongoClient`` constructor or through parameters in your connection string. + +.. include:: /includes/authentication/auth-properties-commas.rst + +.. tabs:: + + .. tab:: MongoClient + :tabid: mongoclient + + First, create a Python dictionary for your authentication mechanism properties, as shown + in the following example: + + .. literalinclude:: /includes/authentication/azure-imds-mongoclient.py + :language: python + :copyable: true + :start-after: # define properties and MongoClient + :end-before: client = MongoClient( + + Then, set the following connection options: + + - ``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. + - ``authMechanism``: Set to ``"MONGODB-OIDC"``. + - ``authMechanismProperties``: Set to the ``properties`` dictionary that you + created in the previous step. + + The following code example shows how to set these options when creating a + ``MongoClient``: + + .. literalinclude:: /includes/authentication/azure-imds-mongoclient.py + :language: python + :copyable: true + :emphasize-lines: 5-10 + + .. tab:: Connection String + :tabid: connectionstring + + Include the following connection 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. + - ``authMechanism``: Set to ``MONGODB-OIDC``. + - ``authMechanismProperties``: Set to + ``ENVIRONMENT:azure,TOKEN_RESOURCE:``. + + The following code example shows how to set these options in your connection string: + + .. literalinclude:: /includes/authentication/azure-imds-connection-string.py + :language: python + :copyable: true + :emphasize-lines: 4-7 + +.. tip:: + + If your application is running on an Azure VM, and only one managed identity is + associated with the VM, you can omit the ``username`` connection option. + +.. _pymongo-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 {+driver-short+}'s built-in GCP +support. + +You can configure OIDC for GCP IMDS in two ways: by passing arguments to the +``MongoClient`` constructor or through parameters in your connection string. + +.. include:: /includes/authentication/auth-properties-commas.rst + +.. tabs:: + + .. tab:: MongoClient + :tabid: mongoclient + + First, create a Python dictionary for your authentication mechanism properties, as shown + in the following example. + + .. literalinclude:: /includes/authentication/gcp-imds-mongoclient.py + :language: python + :copyable: true + :start-after: # define properties and MongoClient + :end-before: client = MongoClient( + + Then, set the following connection options: + + - ``authMechanism``: Set to ``"MONGODB-OIDC"``. + - ``authMechanismProperties``: Set to the ``properties`` dictionary that you + created in the previous step. + + The following code example shows how to set these options when creating a + ``MongoClient``: + + .. literalinclude:: /includes/authentication/gcp-imds-mongoclient.py + :language: python + :copyable: true + :emphasize-lines: 5-9 + + .. tab:: Connection String + :tabid: connectionstring + + Include the following connection options in your connection string: + + - ``authMechanism``: Set to ``MONGODB-OIDC``. + - ``authMechanismProperties``: Set to + ``ENVIRONMENT:gcp,TOKEN_RESOURCE:``. + + The following code example shows how to set these options in your connection string: + + .. literalinclude:: /includes/authentication/gcp-imds-connection-string.py + :language: python + :copyable: true + :emphasize-lines: 4-6 + +.. _pymongo-mongodb-oidc-azure-envs: + +Other Azure Environments +~~~~~~~~~~~~~~~~~~~~~~~~ + +If your application runs on Azure Functions, App Service Environment (ASE), or Azure +Kubernetes Service (AKS), you can use the +`azure-identity `__ package to fetch +authentication credentials. + +First, use pip to install the ``azure-identity`` library, as shown in the +following example: + +.. code-block:: sh + + python3 -m pip install azure-identity + +Next, define a class that inherits from the ``OIDCCallback`` class. This class must +implement a ``fetch()`` method, which returns the OIDC token in the form of an +``OIDCCallbackResult`` object. + +The following example shows how to define a callback class named ``MyCallback``. This class +includes a ``fetch()`` method that retrieves an OIDC token from a file in the standard +service-account token-file location. + +.. literalinclude:: /includes/authentication/azure-envs-mongoclient.py + :language: python + :copyable: true + :start-after: # define callback, properties, and MongoClient + :end-before: properties = {"OIDC_CALLBACK": MyCallback()} + +After you define your callback class, create a Python dictionary that contains one key, +``"OIDC_CALLBACK"``, whose value is an instance of your custom callback class: + +.. literalinclude:: /includes/authentication/azure-envs-mongoclient.py + :language: python + :copyable: true + :start-after: return OIDCCallbackResult(access_token=token) + :end-before: client = MongoClient( + +Finally, set the following connection options by passing arguments to the ``MongoClient`` +constructor: + +- ``authMechanism``: Set to ``"MONGODB-OIDC"``. +- ``authMechanismProperties``: Set to the ``properties`` dictionary that you created in the + previous step. + +.. literalinclude:: /includes/authentication/azure-envs-mongoclient.py + :language: python + :copyable: true + :emphasize-lines: 14-18 + +.. _pymongo-mongodb-oidc-gcp-gke: + +GCP GKE +~~~~~~~ + +If your application runs on a GCP Google Kubernetes Engine (GKE) cluster with a +`configured service account `__, +you can read the OIDC token from the standard service-account token-file location. + +First, define a class that inherits from the ``OIDCCallback`` class. This class must +implement a ``fetch()`` method, which returns the OIDC token in the form of an +``OIDCCallbackResult`` object. + +The following example shows how to define a callback class named ``MyCallback``. This class +includes a ``fetch()`` method that retrieves an OIDC token from a file in the standard +service-account token-file location. + +.. literalinclude:: /includes/authentication/gcp-gke-mongoclient.py + :language: python + :copyable: true + :start-after: # define callback, properties, and MongoClient + :end-before: properties = {"OIDC_CALLBACK": MyCallback()} + +After you define your callback class, create a Python dictionary that contains one key, +``"OIDC_CALLBACK"``, whose value is an instance of your custom callback class: + +.. literalinclude:: /includes/authentication/gcp-gke-mongoclient.py + :language: python + :copyable: true + :start-after: return OIDCCallbackResult(access_token=token) + :end-before: client = MongoClient( + +Finally, set the following connection options by passing arguments to the ``MongoClient`` +constructor: + +- ``authMechanism``: Set to ``"MONGODB-OIDC"``. +- ``authMechanismProperties``: Set to the ``properties`` dictionary that you created + in the previous step. + +.. literalinclude:: /includes/authentication/gcp-gke-mongoclient.py + :language: python + :copyable: true + :emphasize-lines: 11-15 \ No newline at end of file diff --git a/source/security/authentication/scram.txt b/source/security/authentication/scram.txt new file mode 100644 index 00000000..12324db6 --- /dev/null +++ b/source/security/authentication/scram.txt @@ -0,0 +1,105 @@ +.. _pymongo-scram-sha-256: +.. _pymongo-scram-sha-1: + +===== +SCRAM +===== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: salt, default, code example, authorize + +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``. +- ````: Set to ``SCRAM-SHA-1`` or ``SCRAM-SHA-256``. + +To use the code examples on this page, replace these placeholders with your own values. + +.. include:: /includes/authentication/percent-encoding.rst + +Using SCRAM Authentication in Your Application +---------------------------------------------- + +To use SCRAM to authenticate, set the ``authMechanism`` connection option to ``SCRAM-SHA-1`` +or ``SCRAM-SHA-256``. +You can set this option in two ways: by passing an argument to the +``MongoClient`` constructor or through a parameter in your connection string. + +.. tabs:: + + .. tab:: MongoClient + :tabid: mongoclient + + .. code-block:: python + + client = pymongo.MongoClient("mongodb[+srv]://:", + username="", + password="", + authSource="", + authMechanism="") + + .. tab:: Connection String + :tabid: connectionstring + + .. code-block:: python + + uri = ("mongodb[+srv]://:" + "@:/?" + "authSource=" + "&authMechanism=") + client = pymongo.MongoClient(uri) + +API Documentation +----------------- + +To learn more about authenticating your application in {+driver-short+}, +see the following API documentation: + +- `MongoClient <{+api-root+}pymongo/mongo_client.html#pymongo.mongo_client.MongoClient>`__ \ No newline at end of file diff --git a/source/security/authentication/x509.txt b/source/security/authentication/x509.txt new file mode 100644 index 00000000..e40c6861 --- /dev/null +++ b/source/security/authentication/x509.txt @@ -0,0 +1,93 @@ +.. _pymongo-mongodb-x509: + +===== +X.509 +===== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: authorization, 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 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. + +.. include:: /includes/authentication/percent-encoding.rst + +Using X.509 Authentication in Your Application +---------------------------------------------- + +You can set these options in two ways: by passing arguments to the +``MongoClient`` constructor or through parameters in your connection string. + +.. tabs:: + + .. tab:: MongoClient + :tabid: mongoclient + + .. code-block:: python + + client = pymongo.MongoClient("mongodb[+srv]://:", + tls=True, + tlsCertificateKeyFile="", + tlsCertificateKeyFilePassword="", + authMechanism="MONGODB-X509") + + .. tab:: Connection String + :tabid: connectionstring + + .. code-block:: python + + uri = ("mongodb[+srv]://:/?" + "tls=true" + "&tlsCertificateKeyFile=" + "&tlsCertificateKeyFilePassword=" + "&authMechanism=MONGODB-X509") + client = pymongo.MongoClient(uri) + +API Documentation +----------------- + +To learn more about authenticating your application in {+driver-short+}, +see the following API documentation: + +- `MongoClient <{+api-root+}pymongo/mongo_client.html#pymongo.mongo_client.MongoClient>`__ \ No newline at end of file diff --git a/source/security/enterprise-authentication.txt b/source/security/enterprise-authentication.txt deleted file mode 100644 index 230cf214..00000000 --- a/source/security/enterprise-authentication.txt +++ /dev/null @@ -1,468 +0,0 @@ -.. _pymongo-enterprise-auth: - -Enterprise Authentication Mechanisms -==================================== - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: ldap, encryption, principal, tls - -Overview --------- - -MongoDB Enterprise Edition includes authentication mechanisms that aren't -available in MongoDB Community Edition. -In this guide, you can learn how to authenticate to MongoDB by using these -authentication mechanisms. To learn about the other authentication mechanisms available -in MongoDB, see :ref:``. - -.. _pymongo-kerberos: - -Kerberos --------- - -The Generic Security Services API (GSSAPI) provides an interface for Kerberos -authentication. Select the tab that corresponds to your operating system to learn how -to use Kerberos to authenticate. - -.. tabs:: - - .. tab:: Unix - :tabid: unix - - First, use pip or easy_install to install the Python - `kerberos `__ or - `pykerberos `__ module. - - After installing one of these modules, run the ``kinit`` command to obtain and cache - an initial ticket-granting ticket. The following example uses the - ``knit`` command to obtain a ticket-granting ticket for the principal - ``mongodbuser@EXAMPLE.COM``. It then uses the ``klist`` - command to display the principal and ticket in the credentials cache. - - .. code-block:: sh - :copyable: false - - $ kinit mongodbuser@EXAMPLE.COM - mongodbuser@EXAMPLE.COM's Password: - $ klist - Credentials cache: FILE:/tmp/krb5cc_1000 - Principal: mongodbuser@EXAMPLE.COM - - Issued Expires Principal - Feb 9 13:48:51 2013 Feb 9 23:48:51 2013 krbtgt/mongodbuser@EXAMPLE.COM - - After you obtain a ticket-granting ticket, set the following connection options: - - - ``username``: The Kerbos principal to authenticate. Percent-encode this value - before including it in a connection URI. - - ``authMechanism``: Set to ``"GSSAPI"``. - - ``authMechanismProperties``: Optional. By default, MongoDB uses ``mongodb`` as - the authentication service name. To specify a different service name, set - this option to ``"SERVICE_NAME:"``. - - You can set these options in two ways: by passing arguments to the - ``MongoClient`` constructor or through parameters in your connection - string. - - .. include:: /includes/authentication/auth-properties-commas.rst - - .. tabs:: - - .. tab:: MongoClient - :tabid: mongoclient - - .. code-block:: python - - client = pymongo.MongoClient("mongodb://:", - username="mongodbuser@EXAMPLE.COM", - authMechanism="GSSAPI", - authMechanismProperties="SERVICE_NAME:") - - .. tab:: Connection String - :tabid: connectionstring - - .. code-block:: python - - uri = ("mongodb://mongodbuser%40EXAMPLE.COM@:/?" - "&authMechanism=GSSAPI" - "&authMechanismProperties=SERVICE_NAME:") - client = pymongo.MongoClient(uri) - - .. tab:: Windows (SSPI) - :tabid: windows - - First, install the `winkerberos `__ module. - Then, set the following connection options: - - - ``username``: The Kerbos principal to authenticate. Percent-encode this value before including - it in a connection URI. - - ``authMechanism``: Set to ``"GSSAPI"``. - - ``password``: Optional. If the user to authenticate is different from the user - that owns the application process, set this option to the authenticating user's - password. - - ``authMechanismProperties``: Optional. This option includes multiple - authentication properties. To specify more than one of the following properties, - use a comma-delimited list. - - - ``SERVICE_NAME:`` By default, MongoDB uses ``mongodb`` as - the authentication service name. Use this option to specify a different service name. - - ``CANONICALIZE_HOST_NAME``: Whether to use the fully qualified domain name (FQDN) - of the MongoDB host for the server principal. - - ``SERVICE_REALM``: The service realm. Use this option when the user's - realm is different from the service's realm. - - You can set these options in two ways: by passing arguments to the - ``MongoClient`` constructor or through parameters in your connection string. - - .. tabs:: - - .. tab:: MongoClient - :tabid: mongoclient - - .. code-block:: python - - client = pymongo.MongoClient("mongodb://:", - username="mongodbuser@EXAMPLE.COM", - authMechanism="GSSAPI", - password="", - authMechanismProperties="SERVICE_NAME:, - CANONICALIZE_HOST_NAME:true, - SERVICE_REALM:") - - .. tab:: Connection String - :tabid: connectionstring - - .. code-block:: python - - uri = ("mongodb://mongodbuser%40EXAMPLE.COM:" - "@:/?" - "&authMechanism=GSSAPI" - "&authMechanismProperties=" - "SERVICE_NAME:," - "CANONICALIZE_HOST_NAME:true," - "SERVICE_REALM:") - client = pymongo.MongoClient(uri) - -.. _pymongo-sasl: - -PLAIN SASL ----------- - -The PLAIN Simple Authentication and Security Layer (SASL), as defined -by `RFC 4616 `__, is a username-password -authentication mechanism often used with TLS or another encryption layer. - -.. important:: - - PLAIN SASL is a clear-text authentication mechanism. We strongly recommend that you - use TLS/SSL with certificate validation when using PLAIN SASL to authenticate to MongoDB. - - To learn more about how to enable TLS for your connection, see :ref:``. - -To authenticate with SASL, set the ``authMechanism`` connection option to ``PLAIN``. -You can set this option in two ways: by passing an argument to the -``MongoClient`` constructor or through a parameter in your connection string. - -.. include:: /includes/authentication/auth-properties-commas.rst - -.. tabs:: - - .. tab:: MongoClient - :tabid: mongoclient - - .. code-block:: python - - client = pymongo.MongoClient("mongodb://:", - username="", - password="", - authMechanism="PLAIN", - tls=True) - - .. tab:: Connection String - :tabid: connectionstring - - .. code-block:: python - - uri = ("mongodb://:@:/?" - "&authMechanism=PLAIN" - "&tls=true") - client = pymongo.MongoClient(uri) - -.. _pymongo-mongodb-oidc: - -MONGODB-OIDC ------------- - -.. important:: - - The MONGODB-OIDC authentication mechanism requires {+mdb-server+} v7.0 or later running - on a Linux platform. - -{+driver-short+} supports OIDC authentication for **workload identities**. A workload -identity is an identity you assign to a software workload, such as an application, -service, script, or container, to authenticate and access other services and resources. - -The following sections describe how to use the MONGODB-OIDC authentication mechanism to -authenticate to various platforms. - -For more information about the MONGODB-OIDC authentication mechanism, see -:manual:`OpenID Connect Authentication ` and -:manual:`MongoDB Server Parameters ` -in the {+mdb-server+} manual. - -.. note:: - - Because Python's Standard Library doesn't support asynchronous HTTP requests, - all OIDC requests from {+driver-short+} are synchronous and block the ``asyncio`` loop. - -.. _pymongo-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 {+driver-short+}'s built-in Azure -support. - -You can configure OIDC for Azure IMDS in two ways: by passing arguments to the -``MongoClient`` constructor or through parameters in your connection string. - -.. include:: /includes/authentication/auth-properties-commas.rst - -.. tabs:: - - .. tab:: MongoClient - :tabid: mongoclient - - First, create a Python dictionary for your authentication mechanism properties, as shown - in the following example. Replace the ```` placeholder with the - value of the ``audience`` parameter configured on your MongoDB deployment. - - The following code example shows how to set these options in your connection string: - - .. literalinclude:: /includes/authentication/azure-imds-mongoclient.py - :language: python - :copyable: true - :start-after: # define properties and MongoClient - :end-before: client = MongoClient( - - Then, set the following connection options: - - - ``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. - - ``authMechanism``: Set to ``"MONGODB-OIDC"``. - - ``authMechanismProperties``: Set to the ``properties`` dictionary that you - created in the previous step. - - The following code example shows how to set these options when creating a - ``MongoClient``: - - .. literalinclude:: /includes/authentication/azure-imds-mongoclient.py - :language: python - :copyable: true - :emphasize-lines: 5-10 - - .. tab:: Connection String - :tabid: connectionstring - - Include the following connection 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. - - ``authMechanism``: Set to ``MONGODB-OIDC``. - - ``authMechanismProperties``: Set to - ``ENVIRONMENT:azure,TOKEN_RESOURCE:``. - Replace the ```` placeholder with the - value of the ``audience`` parameter configured on your MongoDB deployment. - - The following code example shows how to set these options in your connection string: - - .. literalinclude:: /includes/authentication/azure-imds-connection-string.py - :language: python - :copyable: true - :emphasize-lines: 4-7 - -.. tip:: - - If your application is running on an Azure VM, and only one managed identity is - associated with the VM, you can omit the ``username`` connection option. - -.. _pymongo-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 {+driver-short+}'s built-in GCP -support. - -You can configure OIDC for GCP IMDS in two ways: by passing arguments to the -``MongoClient`` constructor or through parameters in your connection string. - -.. include:: /includes/authentication/auth-properties-commas.rst - -.. tabs:: - - .. tab:: MongoClient - :tabid: mongoclient - - First, create a Python dictionary for your authentication mechanism properties, as shown - in the following example. Replace the ```` placeholder with - the value of the ``audience`` parameter configured on your MongoDB deployment. - - .. literalinclude:: /includes/authentication/gcp-imds-mongoclient.py - :language: python - :copyable: true - :start-after: # define properties and MongoClient - :end-before: client = MongoClient( - - Then, set the following connection options: - - - ``authMechanism``: Set to ``"MONGODB-OIDC"``. - - ``authMechanismProperties``: Set to the ``properties`` dictionary that you - created in the previous step. - - The following code example shows how to set these options when creating a - ``MongoClient``: - - .. literalinclude:: /includes/authentication/gcp-imds-mongoclient.py - :language: python - :copyable: true - :emphasize-lines: 5-9 - - .. tab:: Connection String - :tabid: connectionstring - - Include the following connection options in your connection string: - - - ``authMechanism``: Set to ``MONGODB-OIDC``. - - ``authMechanismProperties``: Set to - ``ENVIRONMENT:gcp,TOKEN_RESOURCE:``. - Replace the ```` placeholder with the - value of the ``audience`` parameter configured on your MongoDB deployment. - - The following code example shows how to set these options in your connection string: - - .. literalinclude:: /includes/authentication/gcp-imds-connection-string.py - :language: python - :copyable: true - :emphasize-lines: 4-6 - -.. _pymongo-mongodb-oidc-azure-envs: - -Other Azure Environments -~~~~~~~~~~~~~~~~~~~~~~~~ - -If your application runs on Azure Functions, App Service Environment (ASE), or Azure -Kubernetes Service (AKS), you can use the -`azure-identity `__ package to fetch -authentication credentials. - -First, use pip to install the ``azure-identity`` library, as shown in the -following example: - -.. code-block:: sh - - python3 -m pip install azure-identity - -Next, define a class that inherits from the ``OIDCCallback`` class. This class must -implement a ``fetch()`` method, which returns the OIDC token in the form of an -``OIDCCallbackResult`` object. - -The following example shows how to define a callback class named ``MyCallback``. This class -includes a ``fetch()`` method that retrieves an OIDC token from a file in the standard -service-account token-file location. - -.. literalinclude:: /includes/authentication/azure-envs-mongoclient.py - :language: python - :copyable: true - :start-after: # define callback, properties, and MongoClient - :end-before: properties = {"OIDC_CALLBACK": MyCallback()} - -After you define your callback class, create a Python dictionary that contains one key, -``"OIDC_CALLBACK"``, whose value is an instance of your custom callback class: - -.. literalinclude:: /includes/authentication/azure-envs-mongoclient.py - :language: python - :copyable: true - :start-after: return OIDCCallbackResult(access_token=token) - :end-before: client = MongoClient( - -Finally, set the following connection options by passing arguments to the ``MongoClient`` -constructor: - -- ``authMechanism``: Set to ``"MONGODB-OIDC"``. -- ``authMechanismProperties``: Set to the ``properties`` dictionary that you created in the - previous step. - -.. literalinclude:: /includes/authentication/azure-envs-mongoclient.py - :language: python - :copyable: true - :emphasize-lines: 14-18 - -.. _pymongo-mongodb-oidc-gcp-gke: - -GCP GKE -~~~~~~~ - -If your application runs on a GCP Google Kubernetes Engine (GKE) cluster with a -`configured service account `__, -you can read the OIDC token from the standard service-account token-file location. - -First, define a class that inherits from the ``OIDCCallback`` class. This class must -implement a ``fetch()`` method, which returns the OIDC token in the form of an -``OIDCCallbackResult`` object. - -The following example shows how to define a callback class named ``MyCallback``. This class -includes a ``fetch()`` method that retrieves an OIDC token from a file in the standard -service-account token-file location. - -.. literalinclude:: /includes/authentication/gcp-gke-mongoclient.py - :language: python - :copyable: true - :start-after: # define callback, properties, and MongoClient - :end-before: properties = {"OIDC_CALLBACK": MyCallback()} - -After you define your callback class, create a Python dictionary that contains one key, -``"OIDC_CALLBACK"``, whose value is an instance of your custom callback class: - -.. literalinclude:: /includes/authentication/gcp-gke-mongoclient.py - :language: python - :copyable: true - :start-after: return OIDCCallbackResult(access_token=token) - :end-before: client = MongoClient( - -Finally, set the following connection options by passing arguments to the ``MongoClient`` -constructor: - -- ``authMechanism``: Set to ``"MONGODB-OIDC"``. -- ``authMechanismProperties``: Set to the ``properties`` dictionary that you created - in the previous step. - -.. literalinclude:: /includes/authentication/gcp-gke-mongoclient.py - :language: python - :copyable: true - :emphasize-lines: 11-15 - -API Documentation ------------------ - -To learn more about using enterprise authentication mechanisms with {+driver-short+}, -see the following API documentation: - -- `MongoClient <{+api-root+}pymongo/mongo_client.html#pymongo.mongo_client.MongoClient>`__ -- `OIDCCallback <{+api-root+}pymongo/auth_oidc.html#pymongo.auth_oidc.OIDCCallback>`__