diff --git a/source/connect/mongoclient.txt b/source/connect/mongoclient.txt index 7c8da8d..8bb3103 100644 --- a/source/connect/mongoclient.txt +++ b/source/connect/mongoclient.txt @@ -40,9 +40,6 @@ Connection URI A standard connection string includes the following components: -.. TODO, add this as last sentence for ``username:password`` description once a kotlin auth page is made: -.. For more information about the ``authSource`` connection option, see :ref:`kotlin-sync-auth`. - .. list-table:: :widths: 20 80 :header-rows: 1 @@ -59,6 +56,8 @@ A standard connection string includes the following components: - Optional. Authentication credentials. If you include these, the client authenticates the user against the database specified in ``authSource``. + For more information about the ``authSource`` connection option, + see :ref:`kotlin-sync-auth`. * - ``host[:port]`` diff --git a/source/includes/security/authentication.kt b/source/includes/security/authentication.kt new file mode 100644 index 0000000..b1acfbf --- /dev/null +++ b/source/includes/security/authentication.kt @@ -0,0 +1,200 @@ +import com.mongodb.* +import com.mongodb.kotlin.client.MongoClient +import org.bson.BsonInt64 +import org.bson.Document + +// SCRAM Authentication +// start-default-cred-string +val mongoClient = + MongoClient.create("mongodb://:@:/?authSource=") +// end-default-cred-string + +// start-default-mongo-cred +val credential = MongoCredential.createCredential( + "", "", "".toCharArray() +) +val settings = MongoClientSettings.builder() + .applyToClusterSettings { builder: ClusterSettings.Builder -> + builder.hosts( + listOf(ServerAddress("", )) + ) + } + .credential(credential) + .build() + +val mongoClient = MongoClient.create(settings) +// end-default-mongo-cred + +// start-scramsha256-cred-string +val mongoClient = + MongoClient.create("mongodb://:@:/?authSource=admin&authMechanism=SCRAM-SHA-256") +// end-scramsha256-cred-string + +// start-scramsha256-mongo-cred +val credential = MongoCredential.createScramSha256Credential( + "", "", "".toCharArray() +) +val settings = MongoClientSettings.builder() + .applyToClusterSettings { builder: ClusterSettings.Builder -> + builder.hosts( + listOf(ServerAddress("", )) + ) + } + .credential(credential) + .build() + +val mongoClient = MongoClient.create(settings) +// end-scramsha256-mongo-cred + +// start-scramsha1-cred-string +val mongoClient = + MongoClient.create("mongodb://:@:/?authSource=admin&authMechanism=SCRAM-SHA-1") +// end-scramsha1-cred-string + +// start-scramsha1-mongo-cred +val credential = MongoCredential.createScramSha1Credential( + "", "", "".toCharArray() +) +val settings = MongoClientSettings.builder() + .applyToClusterSettings { builder: ClusterSettings.Builder -> + builder.hosts( + listOf(ServerAddress("", )) + ) + } + .credential(credential) + .build() + +val mongoClient = MongoClient.create(settings) +// end-scramsha1-mongo-cred + +// AWS Authentication + +// start-aws-sdk-mcred +val credential = MongoCredential.createAwsCredential(null, null) + +val settings = MongoClientSettings.builder() + .applyToClusterSettings { builder: ClusterSettings.Builder -> + builder.hosts( + listOf(ServerAddress("")) + ) + } + .credential(credential) + .build() + +val mongoClient = MongoClient.create(settings) +// end-aws-sdk-mcred + +// start-aws-sdk-cred-string +val mongoClient = + MongoClient.create("mongodb://?authMechanism=MONGODB-AWS") +// end-aws-sdk-cred-string + + +// start-aws-env-mcred +val credential = MongoCredential.createAwsCredential(null, null) + +val settings = MongoClientSettings.builder() + .applyToClusterSettings { builder: ClusterSettings.Builder -> + builder.hosts( + listOf(ServerAddress("")) + ) + } + .credential(credential) + .build() + +val mongoClient = MongoClient.create(settings) +// end-aws-env-mcred + +// start-aws-env-cred-string +val mongoClient = + MongoClient.create("mongodb://?authMechanism=MONGODB-AWS") +// end-aws-env-cred-string + +// start-aws-mcred +val credential = MongoCredential.createAwsCredential("", "".toCharArray()) + +val settings = MongoClientSettings.builder() + .applyToClusterSettings { builder: ClusterSettings.Builder -> + builder.hosts( + listOf(ServerAddress("")) + ) + } + .credential(credential) + .build() + +val mongoClient = MongoClient.create(settings) +// end-aws-mcred + +// start-aws-mcred-wmechprop +val credential = MongoCredential.createAwsCredential("", "".toCharArray()) + .withMechanismProperty("AWS_SESSION_TOKEN", "") + +val settings = MongoClientSettings.builder() + .applyToClusterSettings { builder: ClusterSettings.Builder -> + builder.hosts( + listOf(ServerAddress("")) + ) + } + .credential(credential) + .build() + +val mongoClient = MongoClient.create(settings) +// end-aws-mcred-wmechprop + +// start-aws-lambda-expression +val awsFreshCredentialSupplier: Supplier = Supplier { + // Add your code here to fetch new credentials + + // Return the new credentials + AwsCredential("", "", "") +} + +val credential = MongoCredential.createAwsCredential("", "".toCharArray()) + .withMechanismProperty(MongoCredential.AWS_CREDENTIAL_PROVIDER_KEY, awsFreshCredentialSupplier) + +val settings = MongoClientSettings.builder() + .applyToClusterSettings { builder -> + builder.hosts(listOf(ServerAddress("", ))) + } + .credential(credential) + .build() + +val mongoClient = MongoClient.create(settings) +// end-aws-lambda-expression + +// start-aws-apply-connect-string +val credential = MongoCredential.createAwsCredential("", "".toCharArray()) +val connectionString = ConnectionString("mongodb:///?authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:") + +val settings = MongoClientSettings.builder() + .applyConnectionString(connectionString) + .credential(credential) + .build() + +val mongoClient = MongoClient.create(settings) +// end-aws-apply-connect-string + +// X.509 + +// start-x509-connect-string +val mongoClient = + MongoClient.create("mongodb://:@:/?authSource=&authMechanism=MONGODB-X509&tls=true") +// end-x509-connect-string + +// start-x509-mcred +val credential = MongoCredential.createMongoX509Credential() + +val settings = MongoClientSettings.builder() + .applyToClusterSettings { builder -> + builder.hosts(listOf( + ServerAddress("", )) + ) + } + .applyToSslSettings { builder -> + builder.enabled(true) + } + .credential(credential) + .build() + +val mongoClient = MongoClient.create(settings) +// end-x509-mcred diff --git a/source/includes/security/enterprise-auth.kt b/source/includes/security/enterprise-auth.kt new file mode 100644 index 0000000..698ce9a --- /dev/null +++ b/source/includes/security/enterprise-auth.kt @@ -0,0 +1,147 @@ +import com.mongodb.* +import com.mongodb.kotlin.client.MongoClient +import org.bson.BsonInt64 +import org.bson.Document + +// GSSAPI + +// start-gssapi-connect-string +val connectionString = ConnectionString("@:/?authSource=$external&authMechanism=GSSAPI") +val mongoClient = MongoClient.create(connectionString) +// end-gssapi-connect-string + +// start-gssapi-mongo-cred +val credential = MongoCredential.createGSSAPICredential("") + +val settings = MongoClientSettings.builder() + .applyToClusterSettings { builder -> + builder.hosts(listOf(ServerAddress("", ))) + } + .credential(credential) + .build() + +val mongoClient = MongoClient.create(settings) +// end-gssapi-mongo-cred + +// start-gssapi-properties-connect-string +val connectionString = ConnectionString("@:/?authSource=$external&authMechanism=GSSAPI&authMechanismProperties=SERVICE_NAME:myService") +val mongoClient = MongoClient.create(connectionString) +// end-gssapi-properties-connect-string + +// start-gssapi-service-name-key +val credential = MongoCredential.createGSSAPICredential("") + .withMechanismProperty(MongoCredential.SERVICE_NAME_KEY, "myService") +// end-gssapi-service-name-key + +// start-gssapi-java-subject-key +val loginContext = LoginContext("") +loginContext.login() +val subject: Subject = loginContext.subject + +val credential = MongoCredential.createGSSAPICredential("") + .withMechanismProperty(MongoCredential.JAVA_SUBJECT_KEY, subject) +// end-gssapi-java-subject-key + +// start-gssapi-java-subject-provider +/* All MongoClient instances sharing this instance of KerberosSubjectProvider +will share a Kerberos ticket cache */ +val myLoginContext = "myContext" +/* Login context defaults to "com.sun.security.jgss.krb5.initiate" +if unspecified in KerberosSubjectProvider */ +val credential = MongoCredential.createGSSAPICredential("") + .withMechanismProperty( + MongoCredential.JAVA_SUBJECT_PROVIDER_KEY, + KerberosSubjectProvider(myLoginContext) + ) +// end-gssapi-java-subject-provider + +// LDAP + +// start-ldap-connect-string +val connectionString = ConnectionString(":@:/?authSource=$external&authMechanism=PLAIN") +val mongoClient = MongoClient.create(connectionString) +// end-ldap-connect-string + +// start-ldap-mongo-cred +val credential = MongoCredential.createPlainCredential("", "$external", "".toCharArray()) + +val settings = MongoClientSettings.builder() + .applyToClusterSettings { builder -> + builder.hosts(listOf(ServerAddress("", ))) + } + .credential(credential) + .build() + +val mongoClient = MongoClient.create(settings) +// end-ldap-mongo-cred + +// OIDC + +// start-oidc-azure-connect-str +val connectionString = ConnectionString( + "mongodb://@:/?" + + "?authMechanism=MONGODB-OIDC" + + "&authMechanismProperties=ENVIRONMENT:azure,TOKEN_RESOURCE:") +val mongoClient = MongoClient.create(connectionString) +// end-oidc-azure-connect-str + +// start-oidc-azure-mongo-cred +val credential = MongoCredential.createOidcCredential("") + .withMechanismProperty("ENVIRONMENT", "azure") + .withMechanismProperty("TOKEN_RESOURCE", "") + +val mongoClient = MongoClient.create( + MongoClientSettings.builder() + .applyToClusterSettings { builder -> + builder.hosts(listOf(ServerAddress("", ))) + } + .credential(credential) + .build()) +// end-oidc-azure-mongo-cred + +// start-oidc-gcp-connect-str +val connectionString = ConnectionString( + "mongodb://@:/?" + + "authMechanism=MONGODB-OIDC" + + "&authMechanismProperties=ENVIRONMENT:gcp,TOKEN_RESOURCE:") +val mongoClient = MongoClient.create(connectionString) +// end-oidc-gcp-connect-str + +// start-oidc-gcp-mongo-cred +val credential = MongoCredential.createOidcCredential("") + .withMechanismProperty("ENVIRONMENT", "gcp") + .withMechanismProperty("TOKEN_RESOURCE", "") + +val mongoClient = MongoClient.create( + MongoClientSettings.builder() + .applyToClusterSettings { builder -> + builder.hosts(listOf(ServerAddress("", ))) + } + .credential(credential) + .build()) +// end-oidc-gcp-mongo-cred + +// start-oidc-custom-callback +val credential = MongoCredential.createOidcCredential(null) + .withMechanismProperty("OIDC_CALLBACK") { context: Context -> + val accessToken = "..." + OidcCallbackResult(accessToken) + } +// end-oidc-custom-callback + +// start-oidc-custom-callback-ex +val credential = MongoCredential.createOidcCredential(null) + .withMechanismProperty("OIDC_CALLBACK") { context: Context -> + val accessToken = String(Files.readAllBytes(Paths.get("access-token.dat"))) + OidcCallbackResult(accessToken) + } + +val mongoClient = MongoClient.create( + MongoClientSettings.builder() + .applyToClusterSettings { builder -> + builder.hosts(listOf(ServerAddress("", ))) + } + .credential(credential) + .build() +) +// end-oidc-custom-callback-ex diff --git a/source/index.txt b/source/index.txt index f92711c..908c1c0 100644 --- a/source/index.txt +++ b/source/index.txt @@ -22,6 +22,7 @@ Aggregation Operations Specialized Data Formats Builders + Security In-Use Encryption Compatibility Validate Driver Signatures diff --git a/source/security.txt b/source/security.txt new file mode 100644 index 0000000..08969d5 --- /dev/null +++ b/source/security.txt @@ -0,0 +1,14 @@ + +================ +Secure Your Data +================ + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Authentication + Enterprise Authentication + In-Use Encryption + +.. placeholder \ No newline at end of file diff --git a/source/security/authentication.txt b/source/security/authentication.txt new file mode 100644 index 0000000..cfff198 --- /dev/null +++ b/source/security/authentication.txt @@ -0,0 +1,545 @@ +.. _kotlin-sync-auth: + +========================= +Authentication Mechanisms +========================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: validate credentials, protocols, code example + +Overview +-------- + +In this guide, you can learn how to authenticate to a MongoDB Server by using +each **authentication mechanism** available in the {+driver-long+}. +Authentication is the process by which the driver proves its identity to the +server to ensure security. + +.. note:: Enterprise Authentication Mechanisms + + This page describes the authentication mechanisms available in MongoDB + Community Edition. To authenticate with mechanisms available in + the MongoDB Enterprise Edition, like ``Kerberos`` or ``LDAP``, see the + :ref:`Enterprise Authentication Mechanisms guide `. + +.. _kotlin-sync-auth-default: + +Default +------- + +The default authentication mechanism setting uses one of the following +authentication mechanisms depending on what your MongoDB server supports: + +#. ``SCRAM-SHA-256``: An authentication mechanism that + uses your database username and password, encrypted with the ``SHA-256`` + algorithm +#. ``SCRAM-SHA-1``: An authentication mechanism that + uses your database username and password, encrypted with the ``SHA-1`` + algorithm + +{+mdb-server+} versions 4.0 and later use ``SCRAM-SHA-256`` as the default +authentication mechanism. + +The following code snippets show how to use the default authentication mechanism by +using the following placeholders: + +* ``db_username``: Your MongoDB database username. +* ``db_password``: Your MongoDB database user's password. +* ``hostname``: The network address of your MongoDB deployment, accessible by your client. +* ``port``: The port number of your MongoDB deployment. +* ``authenticationDb``: The MongoDB database that contains your user's + authentication data. If you omit this parameter, the driver uses the + default value ``admin``. + +Select the :guilabel:`Connection String` or the :guilabel:`MongoCredential` +tab below for instructions and sample code for specifying this authentication +mechanism: + +.. tabs:: + + .. tab:: + :tabid: Connection String + + To specify the default authentication mechanism by using a connection + string, omit the mechanism. Your code to instantiate a ``MongoClient`` + should resemble the following: + + .. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :start-after: start-default-cred-string + :end-before: end-default-cred-string + :dedent: + + .. tab:: + :tabid: MongoCredential + + To specify the default authentication mechanism by using the + ``MongoCredential`` class, use the ``createCredential()`` method. + Your code to instantiate a ``MongoClient`` should resemble the following: + + .. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :start-after: start-default-mongo-cred + :end-before: end-default-mongo-cred + :dedent: + +For more information about using SCRAM with MongoDB, see the +:manual:`SCRAM ` section of the {+mdb-server+} manual. + +.. _kotlin-sync-auth-scramsha256: + +SCRAM-SHA-256 +------------- + +.. note:: + + ``SCRAM-SHA-256`` is the default authentication method for {+mdb-server+} + versions 4.0 and later. + +``SCRAM-SHA-256``, as defined by `RFC 7677 `__, +is a Salted Challenge Response Authentication Mechanism +(SCRAM) that uses your username and password, encrypted with the ``SHA-256`` +algorithm, to authenticate your user. + +The following code snippets show how to specify the authentication mechanism by +using the following placeholders: + +* ``db_username``: Your MongoDB database username. +* ``db_password``: Your MongoDB database user's password. +* ``hostname``: The network address of your MongoDB deployment, accessible by your client. +* ``port``: The port number of your MongoDB deployment. +* ``authenticationDb``: The MongoDB database that contains your user's + authentication data. If you omit this parameter, the driver uses the + default value ``admin``. + +Select the :guilabel:`Connection String` or the :guilabel:`MongoCredential` +tab below for instructions and sample code for specifying this authentication +mechanism: + +.. tabs:: + + .. tab:: + :tabid: Connection String + + To specify the ``SCRAM-SHA-256`` authentication mechanism by using a + connection string, assign the ``authMechanism`` parameter the value + ``SCRAM-SHA-256`` in your connection string. Your code to instantiate + a ``MongoClient`` should resemble the following: + + .. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-scramsha256-cred-string + :end-before: end-scramsha256-cred-string + + .. tab:: + :tabid: MongoCredential + + To specify the default authentication mechanism by using the + ``MongoCredential`` class, use the + `createScramSha256Credential() <{+core-api+}/com/mongodb/MongoCredential.html#createScramSha256Credential(java.lang.String,java.lang.String,char[])>`__ + method. Your code to instantiate a ``MongoClient`` should resemble the following: + + .. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-scramsha256-mongo-cred + :end-before: end-scramsha256-mongo-cred + +.. _kotlin-sync-auth-scramsha1: + +SCRAM-SHA-1 +----------- + +.. note:: + ``SCRAM-SHA-1`` is the default authentication method for MongoDB versions + {+mdb-server+} versions 3.6 and earlier. + +``SCRAM-SHA-1``, as defined by `RFC 5802 `__, +is a Salted Challenge Response Authentication Mechanism (SCRAM) that uses your +username and password, encrypted with the ``SHA-1`` algorithm, to authenticate +your user. + +The following code snippets show how to specify the authentication mechanism +by using the following placeholders: + +* ``db_username``: Your MongoDB database username. +* ``db_password``: Your MongoDB database user's password. +* ``hostname``: The network address of your MongoDB deployment, accessible by your client. +* ``port``: The port number of your MongoDB deployment. +* ``authenticationDb``: The MongoDB database that contains your user's + authentication data. If you omit this parameter, the driver uses the + default value ``admin``. + +Select the :guilabel:`Connection String` or the :guilabel:`MongoCredential` +tab below for instructions and sample code for specifying this authentication +mechanism: + +.. tabs:: + + .. tab:: + :tabid: Connection String + + To specify the ``SCRAM-SHA-1`` authentication mechanism by using a + connection string, assign the ``authMechanism`` parameter the value + ``SCRAM-SHA-1`` in your connection string. Your code to instantiate + a ``MongoClient`` should resemble the following: + + .. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-scramsha1-cred-string + :end-before: end-scramsha1-cred-string + + .. tab:: + :tabid: MongoCredential + + To specify the default authentication mechanism by using the + ``MongoCredential`` class, use the + `createScramSha1Credential() <{+core-api+}/com/mongodb/MongoCredential.html#createScramSha1Credential(java.lang.String,java.lang.String,char[])>`__ + method. Your code to instantiate a ``MongoClient`` should resemble the following: + + .. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-scramsha1-mongo-cred + :end-before: end-scramsha1-mongo-cred + +.. _kotlin-sync-auth-x509: + +MONGODB-X509 +------------ + +The ``MONGODB-X509`` authentication mechanism uses +:wikipedia:`TLS ` with X.509 certificates to +authenticate your user. When you specify the ``X.509`` +authentication mechanism, the server authenticates the connection by using +the subject name of the client certificate. + +The following code snippets show how to specify the authentication mechanism +by using the following placeholders: + +* ``hostname``: The network address of your MongoDB deployment, accessible by your client. +* ``port``: The port number of your MongoDB server. +* ``authenticationDb``: The MongoDB database that contains your user's + authentication data. If you omit this parameter, the driver uses the + default value ``admin``. + +Select the :guilabel:`Connection String` or the :guilabel:`MongoCredential` +tab below for instructions and sample code for specifying this authentication +mechanism: + +.. tabs:: + + .. tab:: + :tabid: Connection String + + To specify the ``X.509`` authentication mechanism by using a connection + string, assign the ``authMechanism`` parameter the value ``MONGODB-X509`` + and enable TLS by assigning the ``tls`` + parameter a ``true`` value. Your code to instantiate a ``MongoClient`` + should resemble the following: + + .. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-x509-connect-string + :end-before: end-x509-connect-string + + .. tab:: + :tabid: MongoCredential + + To specify the ``X.509`` authentication mechanism by using the + ``MongoCredential`` class, use the + `createMongoX509Credential() <{+core-api+}/com/mongodb/MongoCredential.html#createMongoX509Credential(java.lang.String)>`__ + method. Also, enable TLS by calling the + `applyToSslSettings() <{+core-api+}/com/mongodb/MongoClientSettings.Builder.html#applyToSslSettings(com.mongodb.Block)>`__ + method and setting the ``enabled`` property to ``true`` in the + `SslSettings.Builder <{+core-api+}/com/mongodb/connection/SslSettings.Builder.html>`__ + block. Your code to instantiate a ``MongoClient`` should resemble the following: + + .. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-x509-mcred + :end-before: end-x509-mcred + +For additional information on configuring your application to use +certificates as well as TLS/SSL options, see the +:ref:`TLS/SSL guide `. + +.. _kotlin-sync-auth-aws: + +MONGODB-AWS +----------- + +.. note:: + + The MONGODB-AWS authentication mechanism is available 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. To learn more about configuring MongoDB Atlas, see the +:atlas:`Set Up Authentication with AWS IAM ` +guide. + +To instruct the driver to use this authentication mechanism, you can either +specify ``MONGODB-AWS`` as a parameter in the connection string or call +the ``MongoCredential.createAwsCredential()`` factory method. + +In the following sections, you can learn different ways to specify the +``MONGODB-AWS`` authentication mechanism and provide your AWS IAM credentials. + +These sections contain code examples that use the following placeholders: + +* ``awsKeyId``: The value of your AWS access key ID +* ``awsSecretKey``: The value of your AWS secret access key +* ``atlasUri``: The network address of your MongoDB Atlas deployment +* ``hostname``: The hostname of your MongoDB Atlas deployment +* ``port``: The port of your MongoDB Atlas deployment +* ``awsSessionToken``: The value of your AWS session token + +.. _kotlin-mongodb-aws-sdk: + +AWS SDK +~~~~~~~ + +.. note:: End of Support for AWS SDK for Java v1 + + The AWS SDK for Java v1 will reach end of support on December 31, 2025. + AWS recommends migrating to AWS SDK for Java v2. For more information, + see the `end of support announcement + `__ + on the AWS site. + +AWS provides software development kits (SDKs) for Java v1 and v2. +The AWS SDK offers the following features: + +- Multiple options for obtaining credentials +- Credential caching, which helps your application avoid rate limiting +- Credential provider management for use with the `Elastic Kubernetes Service `__ + +To use the AWS SDK for ``MONGODB-AWS`` authentication, you must +perform the following steps: + +1. Specify the authentication mechanism. +#. Add the SDK as a dependency to your project. +#. Supply your credentials by using one of the methods in the credential + provider chain. + +To specify the ``MONGODB-AWS`` authentication mechanism by using a ``MongoCredential`` +object, call the ``MongoCredential.createAwsCredential()`` factory method +and add the ``MongoCredential`` instance to your ``MongoClient``, as shown +in the following example: + +.. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-aws-sdk-mcred + :end-before: end-aws-sdk-mcred + :emphasize-lines: 1, 9 + +To specify the ``MONGODB-AWS`` authentication mechanism in the connection string, +add it as a parameter, as shown in the following example: + +.. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-aws-sdk-cred-string + :end-before: end-aws-sdk-cred-string + +To add the AWS SDK as a dependency to your project, see the following +AWS documentation for the version you need: + +- For the **AWS SDK for Java v2**, see the `Setting Up `__ + guide. +- For the **AWS SDK for Java v1**, see the `Getting Started `__ + guide. + +.. note:: + + For the AWS SDK for Java v2, the Java driver currently tests by using the + ``software.amazon.awssdk:auth:2.18.9`` dependency. + + For the AWS SDK for Java v1, the Java driver currently tests by using the + ``com.amazonaws:aws-java-sdk-core:1.12.337`` dependency. + +To supply your credentials, see the following AWS documentation for the +version you need: + +- To learn more about the **AWS SDK for Java v2** class the driver uses to + get the credentials, see the `DefaultCredentialsProvider `__ + API documentation. + + Learn how to supply your credentials to this class from the + `Use the default credential provider chain `__ + section. + +- To learn more about the **AWS SDK for Java v1** class the driver uses to + get the credentials, see the `DefaultAWSCredentialsProviderChain `__ + API documentation. + + Learn how to supply your credentials to this class from the + `Using the Default Credential Provider Chain `__ + section. + +.. note:: + + If you include both v1 and v2 of the AWS SDK for Java in your project, + you must use the v2 methods to supply your credentials. + +.. _kotlin-mongodb-aws-env-variables: + +Specify Your Credentials in the Environment +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can provide your AWS IAM credentials by instructing the driver to +use the ``MONGODB-AWS`` authentication mechanism and by setting the +appropriate environment variables. + +To use the environment variables to supply your credentials, you must perform +the following: + +1. Specify the authentication mechanism. +#. Add the appropriate environment variables. + +You can specify the ``MONGODB-AWS`` authentication mechanism by using a +``MongoCredential`` object or in the connection string. + +To specify the authentication mechanism by using a ``MongoCredential`` object, +call the ``MongoCredential.createAwsCredential()`` factory method and add the +``MongoCredential`` instance to your ``MongoClient``, as shown in the following +example: + +.. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-aws-env-mcred + :end-before: end-aws-env-mcred + :emphasize-lines: 1, 9 + +To specify the ``MONGODB-AWS`` authentication mechanism in the connection +string, add it as a parameter as shown in the following example: + +.. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-aws-env-cred-string + :end-before: end-aws-env-cred-string + +The next examples show how to provide your credentials by setting environment +variables for the following types of authentication: + +- Programmatic access keys +- ECS container credentials +- EC2 container credentials + +The following example shows how you can set your **programmatic access keys** +in 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= + +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 ECS +endpoint relative URI in an environment variable by using ``bash`` or +a similar shell, as shown in the following example: + +.. code-block:: bash + + export AWS_CONTAINER_CREDENTIALS_RELATIVE_URI= + +To authenticate by using **EC2 container credentials**, make sure none of the +aforementioned environment variables are set. The driver obtains the +credentials from the default IPv4 EC2 instance metadata endpoint. + +.. _kotlin-mongodb-aws-mongoclient-configuration: + +Specify Your Credentials in a MongoCredential +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can supply your AWS IAM credentials to a ``MongoClient`` by using a +``MongoCredential`` instance. To construct the ``MongoCredential`` instance +for ``MONGODB-AWS`` authentication, call the +`createAwsCredential() <{+core-api+}/com/mongodb/MongoCredential.html#createAwsCredential(java.lang.String,char%5B%5D)>`__ +factory method. + +You can supply only programmatic access keys to the +``MongoCredential.createAwsCredential()`` method. If you need to supply ECS +or EC2 container credentials, follow the instructions in +:ref:`` or :ref:``. + +To use a ``MongoCredential`` object for ``MONGODB-AWS`` authentication, you +must perform the following steps: + +1. Specify the authentication mechanism. +#. Supply the credentials. + +To specify the authentication mechanism by using a ``MongoCredential`` object, +call the ``MongoCredential.createAwsCredential()`` factory method +and add the ``MongoCredential`` instance to your ``MongoClient``, as shown +in the following example: + +.. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-aws-mcred + :end-before: end-aws-mcred + :emphasize-lines: 1, 9 + +If you need to specify an AWS session token, pass it to the +`withMechanismProperty() <{+core-api+}/com/mongodb/MongoCredential.html#withMechanismProperty(java.lang.String,T)>`__ +method, as shown in the following example: + +.. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-aws-mcred-wmechprop + :end-before: end-aws-mcred-wmechprop + :emphasize-lines: 1, 2, 10 + +To refresh your credentials, you can declare a ``Supplier`` lambda expression +that returns new credentials, as shown in the following example: + +.. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-aws-lambda-expression + :end-before: end-aws-lambda-expression + :emphasize-lines: 4-6, 9 + +If you must provide AWS IAM credentials in a connection string, you can add +it to your ``MongoClientSettings`` object by calling the `applyConnectionString() <{+core-api+}/com/mongodb/MongoClientSettings.Builder.html#applyConnectionString(com.mongodb.ConnectionString)>`__ +method: + +.. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-aws-apply-connect-string + :end-before: end-aws-apply-connect-string + :emphasize-lines: 2, 5 + +Additional Information +---------------------- + +To learn more about authenticating to MongoDB, see +:manual:`Authentication ` in the {+mdb-server+} manual. + +To learn more about managing users of your MongoDB deployment, see +:manual:`Users ` in the {+mdb-server+} manual. diff --git a/source/encrypt-fields.txt b/source/security/encrypt-fields.txt similarity index 100% rename from source/encrypt-fields.txt rename to source/security/encrypt-fields.txt diff --git a/source/security/enterprise-auth.txt b/source/security/enterprise-auth.txt new file mode 100644 index 0000000..512e429 --- /dev/null +++ b/source/security/enterprise-auth.txt @@ -0,0 +1,459 @@ +.. _kotlin-sync-enterprise-auth: + +==================================== +Enterprise Authentication Mechanisms +==================================== + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: ldap, encryption, principal, tls + + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +In this guide, you can learn how to authenticate with MongoDB using each +**authentication mechanism** available exclusively in the MongoDB Enterprise +Edition. + +You can use the following mechanisms with the latest version of MongoDB +Enterprise Edition: + +- :ref:`Kerberos (GSSAPI) ` +- :ref:`LDAP (PLAIN) ` +- :ref:`MONGODB-OIDC ` + +For more information on establishing a connection to your MongoDB cluster, read our +:ref:`Connection Guide `. + +.. _gssapi-auth-mechanism: + +Kerberos (GSSAPI) +----------------- + +The Generic Security Services API (``GSSAPI``) authentication mechanism +allows the user to authenticate to a Kerberos service using the user's +principal name. + +.. note:: + + The method refers to the ``GSSAPI`` authentication mechanism instead + of ``Kerberos`` because the driver authenticates using the + `GSSAPI RFC-4652 `_ SASL + mechanism. + +The following code snippets show how to specify the authentication mechanism, +using the following placeholders: + +* ``Kerberos principal``: Your URL-encoded principal name, e.g. "username%40REALM.ME" +* ``hostname``: The network address of your MongoDB deployment, accessible by your client +* ``port``: Your port number of your MongoDB deployment + +Select the :guilabel:`Connection String` or the :guilabel:`MongoCredential` +tab below for instructions and sample code for specifying this authentication +mechanism: + +.. tabs:: + + .. tab:: + :tabid: Connection String + + To specify the GSSAPI authentication mechanism using a connection + string: + + - Assign the ``authMechanism`` URL parameter to the value ``GSSAPI`` + - *(optional)* Assign the ``authSource`` URL parameter to the value ``$external`` + + .. note:: + + If you specify the ``GSSAPI`` mechanism, you cannot assign + ``authSource`` to any value other than ``$external``. + + Your code to instantiate a ``MongoClient`` should resemble the following: + + .. literalinclude:: /includes/security/enterprise-auth.kt + :language: kotlin + :dedent: + :start-after: start-gssapi-connect-string + :end-before: end-gssapi-connect-string + + .. tab:: + :tabid: MongoCredential + + To specify the GSSAPI authentication mechanism using the + ``MongoCredential`` class, use the ``createGSSAPICredential()`` + method. Your code to instantiate a ``MongoClient`` should resemble the following: + + .. literalinclude:: /includes/security/enterprise-auth.kt + :language: kotlin + :dedent: + :start-after: start-gssapi-mongo-cred + :end-before: end-gssapi-mongo-cred + +In order to acquire a +`Kerberos ticket `__, +the GSSAPI Java libraries require you to specify the realm and Key Distribution +Center (KDC) system properties. See the sample settings in the following example: + +.. code-block:: none + + java.security.krb5.realm=MYREALM.ME + java.security.krb5.kdc=mykdc.myrealm.me + +You may need to specify one or more of the following additional +``MongoCredential`` mechanism properties depending on your Kerberos setup: + +- ``SERVICE_NAME`` +- ``CANONICALIZE_HOST_NAME`` +- ``JAVA_SUBJECT`` +- ``JAVA_SASL_CLIENT_PROPERTIES`` +- ``JAVA_SUBJECT_PROVIDER`` + +.. tabs:: + :hidden: + + .. tab:: + :tabid: Connection String + + .. important:: + + You can only specify the following GSSAPI properties using the + ``MongoCredential``: + + - ``JAVA_SUBJECT`` + - ``JAVA_SASL_CLIENT_PROPERTIES`` + - ``JAVA_SUBJECT_PROVIDER`` + + Select the :guilabel:`MongoCredential` tab to see how to specify + them. + + To specify one of the GSSAPI additional properties, include it in the + connection string as a URL parameter using the format: + ``:``. + + Your code to instantiate a ``MongoClient`` using GSSAPI and additional + properties might resemble the following: + + .. literalinclude:: /includes/security/enterprise-auth.kt + :language: kotlin + :dedent: + :start-after: start-gssapi-properties-connect-string + :end-before: end-gssapi-properties-connect-string + + .. tab:: + :tabid: MongoCredential + + To specify one of the GSSAPI additional properties, call the + ``withMechanismProperty()`` method on your ``MongoCredential`` + instance and pass the property name and value as parameters. Use the + property name constants defined in the ``MongoCredential`` class: + + - `SERVICE_NAME_KEY <{+core-api+}/com/mongodb/MongoCredential.html#SERVICE_NAME_KEY>`__ + - `CANONICALIZE_HOST_NAME_KEY <{+core-api+}/com/mongodb/MongoCredential.html#CANONICALIZE_HOST_NAME_KEY>`__ + - `JAVA_SUBJECT_KEY <{+core-api+}/com/mongodb/MongoCredential.html#JAVA_SUBJECT_KEY>`__ + - `JAVA_SASL_CLIENT_PROPERTIES_KEY <{+core-api+}/com/mongodb/MongoCredential.html#JAVA_SASL_CLIENT_PROPERTIES_KEY>`__ + - `JAVA_SUBJECT_PROVIDER_KEY <{+core-api+}/com/mongodb/MongoCredential.html#JAVA_SUBJECT_PROVIDER_KEY>`__ + + Select the **SERVICE_NAME_KEY** or **JAVA_SUBJECT_KEY** tab to + see sample code to instantiate a ``MongoCredential`` that uses GSSAPI and + the selected property: + + .. tabs:: + + .. tab:: + :tabid: SERVICE_NAME_KEY + + .. literalinclude:: /includes/security/enterprise-auth.kt + :language: kotlin + :dedent: + :start-after: start-gssapi-service-name-key + :end-before: end-gssapi-service-name-key + + .. tab:: + :tabid: JAVA_SUBJECT_KEY + + .. literalinclude:: /includes/security/enterprise-auth.kt + :language: kotlin + :dedent: + :start-after: start-gssapi-java-subject-key + :end-before: end-gssapi-java-subject-key + +By default, the Kotlin driver caches Kerberos tickets by ``MongoClient`` instance. +If your deployment needs to frequently create and destroy ``MongoClient`` instances, +you can change the default Kerberos ticket caching behavior to cache by process +to improve performance. + +.. tabs:: + :hidden: + + .. tab:: + :tabid: Connection String + + To cache Kerberos tickets by process, you must use the ``MongoCredential`` authentication + mechanism, as the connection string authentication mechanism does not support the ``JAVA_SUBJECT_PROVIDER`` + mechanism property. If you would like to cache Kerberos tickets by process, select the :guilabel:`MongoCredential` + tab to learn how to accomplish this. + + .. tab:: + :tabid: MongoCredential + + To cache Kerberos tickets by process, you must specify the ``JAVA_SUBJECT_PROVIDER`` + mechanism property and provide a + `KerberosSubjectProvider `__ + in your ``MongoCredential`` instance. The code to configure the Kotlin driver to cache Kerberos tickets + by process should resemble the following: + + .. literalinclude:: /includes/security/enterprise-auth.kt + :language: kotlin + :dedent: + :start-after: start-gssapi-java-subject-provider + :end-before: end-gssapi-java-subject-provider + +.. note:: + + On Windows, Oracle's JRE uses `LSA `__ + rather than `SSPI `__ + in its implementation of GSSAPI which limits interoperability with + Windows Active Directory and implementations of single sign-on. See the + following articles for more information: + + - `JDK-8054026 `__ + - `JDK-6722928 `__ + - `SO 23427343 `__ + +.. _plain-auth-mechanism: + +LDAP (PLAIN) +------------ + +*Available in MongoDB Enterprise Edition 3.4 and later.* + +You can authenticate to a Lightweight Directory Access Protocol (LDAP) +server using your directory server username and password. + +.. tip:: + + The authentication mechanism is named ``PLAIN`` instead of ``LDAP`` since it + authenticates using the `PLAIN Simple Authentication and Security Layer + (SASL) defined in RFC-4616 `_. + +You can specify this authentication mechanism by setting the ``authMechanism`` +parameter to ``PLAIN`` and including your LDAP username and password in the +:manual:`connection string `. + +The following code snippets show how to specify the authentication mechanism, +using the following placeholders: + +* ``LDAP username``: Your LDAP username +* ``password``: Your LDAP user's password +* ``hostname``: The network address of your MongoDB deployment, accessible by your client +* ``port``: The port number of your MongoDB deployment + +Select the :guilabel:`Connection String` or the :guilabel:`MongoCredential` +tab below for instructions and sample code for specifying this authentication +mechanism: + +.. tabs:: + + .. tab:: + :tabid: Connection String + + To specify the LDAP (PLAIN) authentication mechanism using a connection + string: + + - Assign the ``authMechanism`` URL parameter to the value ``PLAIN`` + - *(optional)* Assign the ``authSource`` URL parameter to the value ``$external`` + + .. note:: + + If you specify the ``PLAIN`` mechanism, you cannot assign + ``authSource`` to any value other than ``$external``. + + Your code to instantiate a ``MongoClient`` should resemble the following: + + .. literalinclude:: /includes/security/enterprise-auth.kt + :language: kotlin + :dedent: + :start-after: start-ldap-connect-string + :end-before: end-ldap-connect-string + + .. tab:: + :tabid: MongoCredential + + To specify the LDAP (PLAIN) authentication mechanism using the + ``MongoCredential`` class, use the ``createPlainCredential()`` + method. Your code to instantiate a ``MongoClient`` should resemble the following: + + .. literalinclude:: /includes/security/enterprise-auth.kt + :language: kotlin + :dedent: + :start-after: start-ldap-mongo-cred + :end-before: end-ldap-mongo-cred + +.. _kotlin-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 to various platforms. + +For more information about the MONGODB-OIDC authentication mechanism, see +:manual:`OpenID Connect Authentication ` and +:manual:`MongoDB Server Parameters ` +in the MongoDB Server manual. + +.. _kotlin-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 either by +using a ``MongoCredential`` instance or by specifying your credentials +in the connection string. + +Select from the :guilabel:`Connection String` or :guilabel:`MongoCredential` tabs to +see the corresponding syntax. + +.. tabs:: + + .. tab:: Connection String + :tabid: mongodb-azure-imds-connection-string + + Replace the ```` placeholder in the + following code with the percent-encoded value of the audience server + parameter configured on your MongoDB deployment. + + The comma (``,``) character and its encoding (``%2C``) are + reserved, and using these characters in a value causes the + driver to interpret commas as delimiters of key-value pairs. + You must specify values that contain commas in a ``MongoCredential`` instance, as + demonstrated in the :guilabel:`MongoCredential` tab. + + .. literalinclude:: /includes/security/enterprise-auth.kt + :language: kotlin + :dedent: + :start-after: start-oidc-azure-connect-str + :end-before: end-oidc-azure-connect-str + + .. tab:: MongoCredential + :tabid: mongodb-azure-mongo-credential + + 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`` server parameter configured on your MongoDB deployment. + + .. literalinclude:: /includes/security/enterprise-auth.kt + :language: kotlin + :dedent: + :start-after: start-oidc-azure-mongo-cred + :end-before: end-oidc-azure-mongo-cred + +.. _kotlin-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 either by +using a ``MongoCredential`` instance or by specifying your credentials +in the connection string. + +Select from the :guilabel:`Connection String` or :guilabel:`MongoCredential` tabs to +see the corresponding syntax. + +.. tabs:: + + .. tab:: Connection String + :tabid: mongodb-gcp-imds-connection-string + + Replace the ```` placeholder in the + following code with the percent-encoded value of the audience server + parameter configured on your MongoDB deployment. + + The comma (``,``) character and its encoding (``%2C``) are + reserved, and using these characters in a value causes the + driver to interpret commas as delimiters of key-value pairs. + You must specify values that contain commas in a ``MongoCredential`` instance, as + demonstrated in the :guilabel:`MongoCredential` tab. + + .. literalinclude:: /includes/security/enterprise-auth.kt + :language: kotlin + :dedent: + :start-after: start-oidc-gcp-connect-str + :end-before: end-oidc-gcp-connect-str + + .. tab:: MongoCredential + :tabid: mongodb-gcp-mongo-credential + + Replace the ```` placeholder with the value of the + ``audience`` server parameter configured on your MongoDB deployment. + + .. literalinclude:: /includes/security/enterprise-auth.kt + :language: kotlin + :dedent: + :start-after: start-oidc-gcp-mongo-cred + :end-before: end-oidc-gcp-mongo-cred + +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. +To do so, use the ``"OIDC_CALLBACK"`` authentication property, as shown in the following +code example: + +.. literalinclude:: /includes/security/enterprise-auth.kt + :language: kotlin + :dedent: + :start-after: start-oidc-custom-callback + :end-before: end-oidc-custom-callback + +The value of the ``"OIDC_CALLBACK"`` property must be a lambda or other implementation +of the ``OidcCallback`` functional interface that accepts an ``OidcCallbackContext`` +as a parameter and returns an ``OidcCallbackResult``. + +The following example uses an example callback to retrieve an OIDC token from a file +named ``"access-token.dat"`` in the local file system: + +.. literalinclude:: /includes/security/enterprise-auth.kt + :language: kotlin + :dedent: + :start-after: start-oidc-custom-callback-ex + :end-before: end-oidc-custom-callback-ex + +API Documentation +----------------- + +To learn more about the classes and methods for authenticating your application +with {+driver-short+}, see the following API documentation: + +- `MongoClient.create() <{+api+}/com.mongodb.kotlin.client/-mongo-client/-factory/index.html>`__ +- `MongoClient <{+api+}/com.mongodb.kotlin.client/-mongo-client/index.html>`__ +- `MongoClientSettings.Builder <{+java-api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html>`__ +- `MongoCredential <{+java-api+}/apidocs/mongodb-driver-core/com/mongodb/MongoCredential.html>`__