diff --git a/snooty.toml b/snooty.toml index ee08024d..12ebd493 100644 --- a/snooty.toml +++ b/snooty.toml @@ -4,7 +4,9 @@ toc_landing_pages = [ "/connect", "/crud", "/monitoring-and-logging", - "/security" + "/security", + "/security/authentication", + "/connect/specify-connection-options" ] intersphinx = [ diff --git a/source/archive-reference-files/fundamentals/connections/connection-guide.txt b/source/archive-reference-files/fundamentals/connections/connection-guide.txt deleted file mode 100644 index fa9089f3..00000000 --- a/source/archive-reference-files/fundamentals/connections/connection-guide.txt +++ /dev/null @@ -1,187 +0,0 @@ -.. _golang-connection-guide: - -================ -Connection Guide -================ - -.. facet:: - :name: genre - :values: tutorial - -.. meta:: - :description: Learn how to use the MongoDB Go Driver to connect to MongoDB. - :keywords: connection string, client options, replica set - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -Overview --------- - -In this guide, you can learn how to connect to a MongoDB instance or -replica set deployment by using the {+driver-short+}. - -You can use the {+driver-short+} to connect to deployments hosted in the -following environments: - -.. include:: /includes/fact-environments.rst - -.. _golang-connection-uri: - --------------- -Connection URI --------------- - -A **connection URI**, also known as a connection string, tells the -driver how to connect to MongoDB and how to behave while connected. - -Parts of a Connection URI -~~~~~~~~~~~~~~~~~~~~~~~~~ - -The following example explains each part of a sample connection URI: - -.. figure:: /includes/figures/connection_uri_parts.png - :alt: Each part of the connection string - -In this example, we use ``mongodb`` for the protocol, which specifies the -:manual:`Standard Connection String Format -`. -You can also use the :manual:`DNS Seed List Connection Format -` if you -want more flexibility of deployment and the ability to change the -servers in rotation without reconfiguring clients. - -The next part of the connection string contains your database username and, if -you are using password-based authentication, your password. Replace the value of -``user`` with your database username and ``pass`` with your password. If you are using an -authentication mechanism that does not require a username and password, omit -this part of the connection URI. - -The next part of the connection string specifies the hostname or IP address and -port of your MongoDB instance. In the preceding example, we use ``sample.host`` -as the hostname and ``27017`` as the port. Replace these values to point to -your MongoDB instance. - -The last part of the connection string specifies connection and authentication -options. In the example, we set two connection options: -``maxPoolSize=20`` and ``w=majority``. To learn more about connection -options, see the :ref:`golang-connection-options` guide. - -Connection Example -~~~~~~~~~~~~~~~~~~ - -To connect to MongoDB, you must create a client. A client manages your -connections and runs database commands. - -.. tip:: Reuse Your Client - - We recommend that you reuse your client across sessions and operations. - You can use the same ``Client`` instance to perform multiple tasks, instead of - creating a new one each time. The ``Client`` type is safe for - concurrent use by multiple `goroutines - `__. To learn more about - how connection pools work in the driver, see the :ref:`FAQ page `. - -You can create a client that uses your connection string and other -client options by passing a ``ClientOptions`` object to the ``Connect()`` -method. - -To specify your connection URI, pass it to the ``ApplyURI()`` -method, which returns a new ``ClientOptions`` instance. To set any other -options, call the relevant helper method from the ``options`` package. - -To learn more about connection options, see the -:ref:`Connection Options section `. To learn -more about creating a client, see the API documentation for `Client -<{+api+}/mongo#Client>`__ and `Connect() <{+api+}/mongo#Connect>`__. - -You can set the {+stable-api+} version as an option to avoid -breaking changes when you upgrade to a new server version. To -learn more about the {+stable-api+} feature, see the :ref:`{+stable-api+} page -`. - -The following code shows how you can create a client that uses an Atlas -connection string and the {+stable-api+} version, connect to MongoDB, and -verify that the connection is successful: - -.. _go-connection-example-code: - -.. literalinclude:: /includes/fundamentals/code-snippets/srv.go - :language: go - -.. tip:: - - Follow the :ref:`Quick Start guide ` - to retrieve your Atlas connection string. - -.. note:: - - To learn about connecting to Atlas Serverless, see the - :ref:`Serverless Instance Limitations page - ` to identify the minimum driver version - required. - --------------------------------- -Other Ways to Connect to MongoDB --------------------------------- - -If you are connecting to a single MongoDB server instance or replica set -that is not hosted on Atlas, see the following sections to find out how to -connect. - -Connect to a MongoDB Server on Your Local Machine -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. include:: /includes/localhost-connection.rst - -To test whether you can connect to your server, replace the connection -string with your localhost connection string in the preceding code example. - -Connect to a Replica Set -~~~~~~~~~~~~~~~~~~~~~~~~ - -A MongoDB replica set deployment is a group of connected instances that -store the same set of data. This configuration provides data -redundancy and high data availability. - -To connect to a replica set deployment, specify the hostname and port numbers -of each instance, separated by commas, and the replica set name as the value -of the ``replicaSet`` parameter in the connection string. In the following -example, the hostnames are ``host1``, ``host2``, and ``host3``, and the -port numbers are all ``27017``. The replica set name is ``myRS``. - -.. code-block:: none - - mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myRS - -When connecting to a replica set, the driver takes the following actions by default: - -- Discovers all replica set members when given the address of any one member. -- Dispatches operations to the appropriate member, such as instructions - to write against the **primary**. - -.. tip:: - - You can specify just one host to connect to a replica set. - However, to ensure connectivity when the specified host - is unavailable, you should provide the full list of hosts. - -Direct Connection -````````````````` - -To force operations on the host designated in the connection URI, -specify the ``directConnection`` option. Direct connections exhibit the -following behavior: - -- They don't support SRV strings. -- They fail on writes when the specified host is not the **primary**. -- They require you to specify a :manual:`secondary read preference - ` when the - specified host isn't the **primary** node. - -.. note:: Replica Set in Docker - - .. sharedinclude:: dbx/docker-replica-set.rst diff --git a/source/connect.txt b/source/connect.txt index 61cd063a..5be7092e 100644 --- a/source/connect.txt +++ b/source/connect.txt @@ -1,9 +1,18 @@ -.. _go-connect: +.. _golang-connection-guide: .. _golang-connection: +.. _golang-connect: -================== -Connect to MongoDB -================== +================ +Connection Guide +================ + +.. facet:: + :name: genre + :values: tutorial + +.. meta:: + :description: Learn how to use the MongoDB Go Driver to connect to MongoDB. + :keywords: connection string, client options, replica set, code example .. contents:: On this page :local: @@ -11,26 +20,181 @@ Connect to MongoDB :depth: 2 :class: singlecol -.. meta:: - :description: Learn how to use {+driver-short+} to connect to MongoDB. - :keywords: client, ssl - .. toctree:: :titlesonly: :maxdepth: 1 Create a MongoClient Choose a Connection Target - Connection Options + Connection Options Connection Troubleshooting Overview -------- -Learn how to use the {+driver-short+} to configure your application's -connection to a MongoDB deployment in the following sections: +In this guide, you can learn how to connect to a MongoDB instance or +replica set deployment by using the {+driver-short+}. + +You can use the {+driver-short+} to connect to deployments hosted in the +following environments: + +.. include:: /includes/fact-environments.rst + +.. _golang-connection-uri: + +-------------- +Connection URI +-------------- + +A **connection URI**, also known as a connection string, tells the +driver how to connect to MongoDB and how to behave while connected. + +Parts of a Connection URI +~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following image explains each part of a sample connection URI: + +.. figure:: /includes/figures/connection_uri_parts.png + :alt: Each part of the connection string + +In this example, we use ``mongodb`` for the protocol, which specifies the +:manual:`Standard Connection String Format +`. +You can also use the :manual:`SRV Connection Format +` if you +want more flexibility of deployment and the ability to change the +servers in rotation without reconfiguring clients. + +The next part of the connection string contains your database username and, if +you are using password-based authentication, your password. Replace the value of +``user`` with your database username and ``pass`` with your password. If you are using an +authentication mechanism that does not require a username and password, omit +this part of the connection URI. + +The next part of the connection string specifies the hostname or IP address and +port of your MongoDB instance. In the preceding example, we use ``sample.host`` +as the hostname and ``27017`` as the port. Replace these values to point to +your MongoDB instance. + +The last part of the connection string specifies connection and authentication +options. In the example, we set two connection options: +``maxPoolSize=20`` and ``w=majority``. To learn more about connection +options, see the :ref:`golang-connection-options` guide. + +Connection Example +~~~~~~~~~~~~~~~~~~ + +To connect to MongoDB, you must create a client. A client manages your +connections and runs database commands. + +.. tip:: Reuse Your Client + + We recommend that you reuse your client across sessions and operations. + You can use the same ``Client`` instance to perform multiple tasks, instead of + creating a new one each time. The ``Client`` type is safe for + concurrent use by multiple `goroutines + `__. + +.. TODO, Add back this line when Connection Pools page is made: To learn more about + how connection pools work in the driver, see the :ref:`Connection Pools guide `. + +You can create a client that uses your connection string and other +client options by passing a ``ClientOptions`` object to the ``Connect()`` +method. + +To specify your connection URI, pass it to the ``ApplyURI()`` +method, which returns a new ``ClientOptions`` instance. To set any other +options, call the relevant helper method from the ``options`` package. + +To learn more about connection options, see the +:ref:`Connection Options section `. To learn +more about creating a client, see the API documentation for `Client +<{+api+}/mongo#Client>`__ and `Connect() <{+api+}/mongo#Connect>`__. + +You can set the {+stable-api+} version as an option to avoid +breaking changes when you upgrade to a new server version. To +learn more about the {+stable-api+} feature, see the :ref:`{+stable-api+} page +`. + +The following code shows how you can create a client that uses an Atlas +connection string and the {+stable-api+} version, connect to MongoDB, and +verify that the connection is successful: + +.. _go-connection-example-code: + +.. literalinclude:: /includes/fundamentals/code-snippets/srv.go + :language: go + +.. tip:: + + Follow the :ref:`Quick Start guide ` + to retrieve your Atlas connection string. + +.. note:: + + To learn about connecting to Atlas Serverless, see the + :ref:`Serverless Instance Limitations page + ` to identify the minimum driver version + required. + +-------------------------------- +Other Ways to Connect to MongoDB +-------------------------------- + +If you are connecting to a single MongoDB server instance or replica set +that is not hosted on Atlas, see the following sections to find out how to +connect. + +Connect to a MongoDB Server on Your Local Machine +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. include:: /includes/localhost-connection.rst + +To test whether you can connect to your server, replace the connection +string with your localhost connection string in the preceding code example. + +Connect to a Replica Set +~~~~~~~~~~~~~~~~~~~~~~~~ + +A MongoDB replica set deployment is a group of connected instances that +store the same set of data. This configuration provides data +redundancy and high data availability. + +To connect to a replica set deployment, specify the hostname and port numbers +of each instance, separated by commas, and the replica set name as the value +of the ``replicaSet`` parameter in the connection string. In the following +example, the hostnames are ``host1``, ``host2``, and ``host3``, and the +port numbers are all ``27017``. The replica set name is ``myRS``. + +.. code-block:: none + + mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myRS + +When connecting to a replica set, the driver takes the following actions by default: + +- Discovers all replica set members when given the address of any one member. +- Dispatches operations to the appropriate member, such as instructions + to write against the **primary**. + +.. tip:: + + You can specify just one host to connect to a replica set. + However, to ensure connectivity when the specified host + is unavailable, provide the full list of hosts. + +Direct Connection +````````````````` + +To force operations on the host designated in the connection URI, +specify the ``directConnection`` option. Direct connections exhibit the +following behavior: + +- They don't support SRV strings. +- They fail on writes when the specified host is not the **primary**. +- They require you to specify a :manual:`secondary read preference + ` when the + specified host isn't the **primary** node. + +.. note:: Replica Set in Docker -- :ref:`golang-connection-guide` -- :ref:`golang-connection-options` -- :ref:`golang-network-compression` -- :ref:`golang-connection-troubleshooting` + .. sharedinclude:: dbx/docker-replica-set.rst diff --git a/source/connect/connection-options.txt b/source/connect/connection-options.txt deleted file mode 100644 index 0ab8d363..00000000 --- a/source/connect/connection-options.txt +++ /dev/null @@ -1,14 +0,0 @@ -================== -Connection Options -================== - -.. toctree:: - :titlesonly: - :maxdepth: 1 - - Specify Connection Options - Compress Network Traffic - Customize Server Selection - Stable API - Limit Server Execution Time - Connection Pools diff --git a/source/connect/connection-options/connection-pools.txt b/source/connect/connection-options/connection-pools.txt index f6d55bcc..c4618800 100644 --- a/source/connect/connection-options/connection-pools.txt +++ b/source/connect/connection-options/connection-pools.txt @@ -1,3 +1,4 @@ +.. _golang-connection-pools: ================ Connection Pools diff --git a/source/connect/connection-options/specify-connection-options.txt b/source/connect/specify-connection-options.txt similarity index 92% rename from source/connect/connection-options/specify-connection-options.txt rename to source/connect/specify-connection-options.txt index 569a671a..06cb5452 100644 --- a/source/connect/connection-options/specify-connection-options.txt +++ b/source/connect/specify-connection-options.txt @@ -17,6 +17,17 @@ Specify Connection Options :depth: 2 :class: singlecol +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Specify Connection Options + Compress Network Traffic + Customize Server Selection + Stable API + Limit Server Execution Time + Connection Pools + Overview -------- diff --git a/source/data-formats.txt b/source/data-formats.txt index d34d40ff..ff83ad10 100644 --- a/source/data-formats.txt +++ b/source/data-formats.txt @@ -1,4 +1,4 @@ -.. _node-data-formats: +.. _golang-data-formats: ======================== Specialized Data Formats diff --git a/source/get-started.txt b/source/get-started.txt index fafad122..76d91eb3 100644 --- a/source/get-started.txt +++ b/source/get-started.txt @@ -10,7 +10,7 @@ Getting Started with Go .. meta:: :description: Learn how to create an app to connect to MongoDB deployment by using the Go driver. - :keywords: node.js + :keywords: go .. contents:: On this page :local: diff --git a/source/security/authentication.txt b/source/security/authentication.txt index b97791f7..08b310b0 100644 --- a/source/security/authentication.txt +++ b/source/security/authentication.txt @@ -1,5 +1,6 @@ .. _golang-enterprise-authentication-mechanisms: .. _golang-authentication-mechanisms: +.. _golang-authentication: ========================= Authentication Mechanisms @@ -19,8 +20,6 @@ Authentication Mechanisms LDAP (PLAIN) Kerberos (GSSAPI) -.. TODO make sure correct - Overview -------- @@ -72,4 +71,4 @@ a mechanism to learn more about how to use it with your application. * - :ref:`` - No - Yes - - No \ No newline at end of file + - No diff --git a/source/security/authentication/aws-iam.txt b/source/security/authentication/aws-iam.txt new file mode 100644 index 00000000..76256b20 --- /dev/null +++ b/source/security/authentication/aws-iam.txt @@ -0,0 +1,149 @@ +.. _golang-mongodb-aws: +.. _golang-authentication-aws: + +================================ +AWS IAM Authentication Mechanism +================================ + +.. contents:: On this page + :local: + :backlinks: none + :depth: 3 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: atlas, amazon web services, code example + +Overview +-------- + +The ``MONGODB-AWS`` authentication mechanism uses Amazon Web Services +Identity and Access Management (AWS IAM) credentials to authenticate a user to MongoDB. +You can use this mechanism only when authenticating to MongoDB Atlas. + +.. tip:: Configure Atlas for AWS IAM Authentication + + To learn more about configuring MongoDB Atlas for AWS IAM authentication, see + :atlas:`Set Up Authentication with AWS IAM ` in + the Atlas documentation. + +Specify MONGODB-AWS Authentication +---------------------------------- + +To connect to a MongoDB instance with ``MONGODB-AWS`` authentication enabled, +specify the ``MONGODB-AWS`` authentication mechanism. + +The driver checks for your credentials in the following sources in the +order listed: + +1. Connection string. +#. Environment variables. +#. Web identity token file. +#. AWS ECS endpoint specified in the + ``AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`` environment variable. +#. AWS EC2 endpoint. To learn more, see `IAM Roles for Tasks + `__ + in the AWS documentation. + +.. important:: + + The driver obtains the credentials only from the first source in which they are found. + For example, if you specify your AWS credentials in the connection string, the + driver ignores any credentials that you specify in environment variables. + +.. tabs:: + + .. tab:: Connection String + :tabid: connection string + + .. tip:: + + The following examples set the appropriate credentials by using the ``SetAuth()`` + method. You can also specify these credentials by using the ``ApplyURI()`` + method. If you use the ``ApplyURI()`` method you must URL encode the username + and password to ensure they are correctly parsed. + + To connect to your MongoDB instance using your AWS IAM credentials, perform the + following steps: + + - Assign the ``AuthMechanism`` option the value ``MONGODB-AWS`` + - Assign the ``Username`` option the value of your ``accessKeyID`` + - Assign the ``Password`` option the value of your ``secretAccessKey`` + + .. literalinclude:: /includes/fundamentals/code-snippets/authentication/aws-connection-string.go + :language: go + + If you must specify an AWS session token, use the temporary + credentials returned from an `assume role request `__. + + To use temporary credentials, assign the value of your ``sessionToken`` to + the ``AuthMechanismProperties`` option: + + .. literalinclude:: /includes/fundamentals/code-snippets/authentication/aws-connection-string-session-token.go + :language: go + + .. tab:: Environment Variables + :tabid: environment variables + + To authenticate to your MongoDB instance using AWS credentials stored in + environment variables, use a shell to set the variables as follows: + + .. code-block:: bash + + export AWS_ACCESS_KEY_ID= + export AWS_SECRET_ACCESS_KEY= + export AWS_SESSION_TOKEN= + + .. note:: + + If you don't require an AWS session token for the role you're + authenticating with, omit the line containing ``AWS_SESSION_TOKEN``. + + After you've set the preceding environment variables, specify the ``MONGODB-AWS`` + authentication mechanism as shown in the following example: + + .. literalinclude:: /includes/fundamentals/code-snippets/authentication/aws-environment-variables.go + :language: go + + .. tab:: Web Identity Token File + :tabid: web-identity-token-file + + You can use the OpenID Connect (OIDC) token obtained from a web + identity provider to authenticate to Amazon Elastic Kubernetes + Service (EKS) or other services. To use an OIDC token, create or + locate the file that contains your token. Then, set the following + environment variables: + + - ``AWS_WEB_IDENTITY_TOKEN_FILE``: Set to the absolute path of the + file that contains your OIDC token. + + - ``AWS_ROLE_ARN``: Set to the IAM role used to connect to your + cluster. For example: ``arn:aws:iam::111122223333:role/my-role``. + + The following shell command sets these environment variables: + + .. code-block:: bash + + export AWS_WEB_IDENTITY_TOKEN_FILE= + export AWS_ROLE_ARN= + + After you set the preceding environment variables, specify the ``MONGODB-AWS`` + authentication mechanism as shown in the following example: + + .. literalinclude:: /includes/fundamentals/code-snippets/authentication/aws-environment-variables.go + :language: go + +API Documentation +----------------- + +To learn more about any of the methods or types discussed on this +page, see the following API documentation: + +- `Client <{+api+}/mongo#Client>`__ +- `Credential <{+api+}/mongo/options#Credential>`__ +- `SetAuth() <{+api+}/mongo/options#ClientOptions.SetAuth>`__ +- `ClientOptions <{+api+}/mongo/options#ClientOptions>`__ diff --git a/source/security/authentication/kerberos.txt b/source/security/authentication/kerberos.txt new file mode 100644 index 00000000..8c3a8718 --- /dev/null +++ b/source/security/authentication/kerberos.txt @@ -0,0 +1,128 @@ +.. _golang-kerberos: +.. _golang-authentication-kerberos: + +========================================== +Kerberos (GSSAPI) Authentication Mechanism +========================================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: 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: + +- ``kerberos_principal``: Your Kerberos principal. A sample username is ``myuser@KERBEROS.EXAMPLE.COM``. +- ``password``: Your Kerberos user's password. You can also store your + password in a ``keytab`` file to avoid exposing your + password in your code. +- ``connection_uri``: Your connection string URI. + +Specify Kerberos (GSSAPI) Authentication +---------------------------------------- + +You must use the ``gssapi`` `build tag `__ +and specify `cgo support `__ during +compilation to use Kerberos authentication. ``cgo`` support is enabled by +default unless you previously set environment variables to +cross-compile to a different platform. To use the ``gssapi`` build tag, +compile your code with the following command: + +.. code-block:: sh + + go build -tags gssapi + +The following code shows how you can define a ``Credential`` struct to +authenticate to Kerberos and create a client with your authentication +preferences: + +.. code-block:: go + + credential := options.Credential{ + AuthMechanism: "GSSAPI", + Username: "", + Password: "", + PasswordSet: true, + } + + uri := "" + clientOpts := options.Client().ApplyURI(uri).SetAuth(credential) + + client, err := mongo.Connect(clientOpts) + +You can omit a password or the ``PasswordSet`` field in +your ``Credential`` struct if you store authentication keys in +``keytab`` files. You can initialize a credential cache for +authenticating the Kerberos principal using the ``kinit`` binary. To +learn more about the ``kinit`` binary, see the `Oracle documentation +`__. + +The following command shows how you can invoke a credential cache for a +sample username: + +.. code-block:: sh + + kinit myuser@KERBEROS.EXAMPLE.COM + +You can alternatively authenticate using a connection string URI, +specifying your :wikipedia:`URL-encoded ` Kerberos +principal, password, and ``hostname``, the network address of your +MongoDB server: + +.. code-block:: go + + uri := "mongodb://:@/?authMechanism=GSSAPI" + +Set Custom SERVICE_NAME and SERVICE_REALM Fields +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can specify more properties with your authentication +mechanism using the ``AuthMechanismProperties`` field in the +``Credential`` struct. The default service name for Kerberos is +"mongodb". The following code shows how you can set custom values +for the ``SERVICE_NAME`` and ``SERVICE_REALM`` fields when defining a +``Credential`` struct: + +.. code-block:: go + + credential := options.Credential{ + AuthMechanism: "GSSAPI", + Username: "", + Password: "", + AuthMechanismProperties: map[string]string{ + "SERVICE_REALM": "", + "SERVICE_NAME": "", + }, + } + +For more properties, see the +:manual:`Server manual entry on authentication properties `. + +API Documentation +----------------- + +To learn more about any of the methods or types discussed on this +page, see the following API documentation: + +- `Client <{+api+}/mongo#Client>`__ +- `Credential <{+api+}/mongo/options#Credential>`__ +- `SetAuth() <{+api+}/mongo/options#ClientOptions.SetAuth>`__ +- `ClientOptions <{+api+}/mongo/options#ClientOptions>`__ diff --git a/source/security/authentication/ldap.txt b/source/security/authentication/ldap.txt new file mode 100644 index 00000000..2a13ef26 --- /dev/null +++ b/source/security/authentication/ldap.txt @@ -0,0 +1,92 @@ +.. _golang-LDAP: +.. _golang-authentication-ldap: + +===================================== +LDAP (PLAIN) Authentication Mechanism +===================================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: 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. + +Code Placeholders +~~~~~~~~~~~~~~~~~ + +The code examples on this page use the following placeholders: + +- ``ldap_username``: Your LDAP username +- ``password``: Your LDAP password +- ``connection_uri``: Your connection string URI + +Specify LDAP Authentication +--------------------------- + +You can authenticate to a Lightweight Directory Access Protocol (LDAP) server +using your directory server username and password. + +.. warning:: + + This authentication mechanism sends the password to the server in + plaintext, so use this mechanism only with TLS connections. + +The following code shows how you can define a ``Credential`` struct to +authenticate to LDAP and create a client with your authentication +preferences: + +.. code-block:: go + + credential := options.Credential{ + AuthMechanism: "PLAIN", + Username: "", + Password: "", + } + + uri := "" + clientOpts := options.Client().ApplyURI(uri).SetAuth(credential) + + client, err := mongo.Connect(clientOpts) + +You can alternatively authenticate using a connection string URI, +specifying your LDAP username, password, and ``hostname``, the network +address of your MongoDB server: + +.. code-block:: go + + uri := "mongodb://:@/?authMechanism=PLAIN" + +.. note:: + + The method refers to PLAIN instead of LDAP since it + authenticates using the PLAIN Simple Authentication and Security Layer + (SASL) defined in `RFC-4616 `__. + +API Documentation +----------------- + +To learn more about any of the methods or types discussed on this +page, see the following API documentation: + +- `Client <{+api+}/mongo#Client>`__ +- `Credential <{+api+}/mongo/options#Credential>`__ +- `SetAuth() <{+api+}/mongo/options#ClientOptions.SetAuth>`__ +- `ClientOptions <{+api+}/mongo/options#ClientOptions>`__ diff --git a/source/security/authentication/oidc.txt b/source/security/authentication/oidc.txt new file mode 100644 index 00000000..dcc566ad --- /dev/null +++ b/source/security/authentication/oidc.txt @@ -0,0 +1,386 @@ +.. _golang-mongodb-oidc: +.. _golang-authentication-oidc: + +============================= +OIDC Authentication Mechanism +============================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: oidc, encryption, tls + :description: Explore sample code for connecting to MongoDB using the enterprise authentication mechanism MONGODB-OIDC with the MongoDB Go Driver. + +Overview +-------- + +.. important:: + + The MONGODB-OIDC authentication mechanism requires {+mdb-server+} + v7.0 or later running on a Linux platform. + +The {+driver-short+} supports OpenID Connect (**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. + +To learn more about the MONGODB-OIDC authentication mechanism, see +:manual:`OpenID Connect Authentication ` and +:manual:`MongoDB Server Parameters ` +in the {+mdb-server+} manual. + +.. _golang-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 configure OIDC for Azure IMDS in the following ways: + +- Create a ``Credential`` struct and pass it to the + ``SetAuth()`` method when you create a client +- Set parameters in your connection string + +.. include:: /includes/authentication/auth-properties-commas.rst + +.. tabs:: + + .. tab:: Credential + :tabid: credential struct + + First, create a map to store 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. + + .. code-block:: go + + props := map[string]string{ + "ENVIRONMENT": "azure", + "TOKEN_RESOURCE": "", + } + + Then, set the following ``Credential`` struct fields: + + - ``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 ``props`` map that you + previously created. + + The following code example shows how to set these options when creating a + ``Client``: + + .. literalinclude:: /includes/authentication/azure-imds-client.go + :dedent: + :language: go + :copyable: true + :start-after: start-azure-imds-client + :end-before: end-azure-imds-client + :emphasize-lines: 9-11 + + .. 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: + + .. code-block:: go + + uri := "mongodb://:/?" + + "username=" + + "&authMechanism=MONGODB-OIDC" + + "&authMechanismProperties=ENVIRONMENT:azure,TOKEN_RESOURCE:" + + client, err := mongo.Connect(options.Client().ApplyURI(uri)) + if err != nil { + panic(err) + } + +.. 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. + +.. _golang-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 configure OIDC for GCP IMDS in the following ways: + +- Create a ``Credential`` struct and pass it to the + ``SetAuth()`` method when you create a client +- Set parameters in your connection string + +.. include:: /includes/authentication/auth-properties-commas.rst + +.. tabs:: + + .. tab:: Credential + :tabid: credential struct + + First, create a map to store 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. + + .. code-block:: go + + props := map[string]string{ + "ENVIRONMENT": "gcp", + "TOKEN_RESOURCE": "", + } + + Then, set the following ``Credential`` struct fields: + + - ``AuthMechanism``: Set to ``"MONGODB-OIDC"``. + - ``AuthMechanismProperties``: Set to the ``props`` map that you + previously created. + + The following code example shows how to set these options when creating a + ``Client``: + + .. literalinclude:: /includes/authentication/gcp-imds-client.go + :language: go + :dedent: + :copyable: true + :start-after: start-gcp-imds-client + :end-before: end-gcp-imds-client + :emphasize-lines: 9-10 + + .. 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: + + .. code-block:: go + + uri := "mongodb://:/?" + + "&authMechanism=MONGODB-OIDC" + + "&authMechanismProperties=ENVIRONMENT:gcp,TOKEN_RESOURCE:" + + client, err := mongo.Connect(options.Client().ApplyURI(uri)) + if err != nil { + panic(err) + } + +.. _golang-mongodb-oidc-custom-callback: + +Custom Callback +~~~~~~~~~~~~~~~ + +The {+driver-short+} doesn't offer built-in support for all platforms, +including the AWS Elastic Kubernetes Service (EKS). To authenticate +against unsupported platforms, you must define a custom callback +function to use OIDC to authenticate. In the driver, you can define an +``options.OIDCCallback`` function and set it as the value of the +``OIDCMachineCallback`` struct field in your ``Credential`` struct. + +The following example defines a custom callback for an EKS +cluster with a configured IAM OIDC provider. The access token is +read from a path set in the ``AWS_WEB_IDENTITY_TOKEN_FILE`` +environment variable: + +.. literalinclude:: /includes/authentication/eks-custom-callback.go + :language: go + :dedent: + :copyable: true + :start-after: start-custom-callback + :end-before: end-custom-callback + +Then, you can create a ``Credential`` struct that uses the EKS callback +function that you defined: + +.. literalinclude:: /includes/authentication/eks-custom-callback.go + :language: go + :dedent: + :copyable: true + :start-after: start-credential-callback + :end-before: end-credential-callback + :emphasize-lines: 6 + +.. _golang-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 `azidentity +`__ +module to fetch authentication credentials. + +First, install the ``azidentity`` module by running the +following command: + +.. code-block:: sh + + go get -u github.com/Azure/azure-sdk-for-go/sdk/azidentity + +Your ``OIDCCallback`` function must return an ``OIDCCredential`` +instance that uses the ``AccessToken`` generated from the ``azidentity`` +package. See the preceding :ref:`golang-mongodb-oidc-custom-callback` +section for an example that implements a custom callback to retrieve an +access token and then creates a ``Credential``. + +.. _golang-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 the ``OIDCCallback`` function. This function reads the +OIDC token and returns an ``OIDCCredential`` instance. + +The following example defines a callback function named ``gkeCallback``. +The function retrieves an OIDC token from a file in the standard +service-account token-file location: + +.. literalinclude:: /includes/authentication/gke-callback.go + :language: go + :copyable: true + :dedent: + :start-after: start-callback + :end-before: end-callback + +Then, you can create a ``Credential`` struct that uses the the GKE +callback function that you defined: + +.. literalinclude:: /includes/authentication/gke-callback.go + :language: go + :copyable: true + :dedent: + :start-after: start-credential-callback + :end-before: end-credential-callback + :emphasize-lines: 6 + +.. _golang-kubernetes-oidc: + +Kubernetes +~~~~~~~~~~ + +If your application runs on a Kubernetes cluster with a configured service account, +you can authenticate to MongoDB by using the {+driver-short+}'s built-in Kubernetes +support. To learn more about how to configure a service account, see the +`Managing Service Accounts `__ +guide in the Kubernetes documentation. + +You can configure OIDC for Kubernetes in the following ways: + +- Create a ``Credential`` struct and pass it to the + ``SetAuth()`` method when you create a client +- Set parameters in your connection string + +.. include:: /includes/authentication/auth-properties-commas.rst + +.. tabs:: + + .. tab:: Credential + :tabid: credential struct + + First, create a map to store your authentication + mechanism properties, as shown in the following example: + + .. code-block:: go + + props := map[string]string{ + "ENVIRONMENT": "k8s", + } + + Then, set the following ``Credential`` struct fields: + + - ``AuthMechanism``: Set to ``"MONGODB-OIDC"``. + - ``AuthMechanismProperties``: Set to the ``props`` map that you + previously created. + + The following code example shows how to set these options when creating a + ``Client``: + + .. literalinclude:: /includes/authentication/kubernetes.go + :language: go + :dedent: + :copyable: true + :start-after: start-kubernetes + :end-before: end-kubernetes + + .. tab:: Connection String + :tabid: connectionstring + + Include the following connection options in your connection string: + + - ``authMechanism``: Set to ``MONGODB-OIDC``. + - ``authMechanismProperties``: Set to ``ENVIRONMENT:k8s``. + + The following code example shows how to set these options in your connection string: + + .. code-block:: go + + uri := "mongodb://:/?" + + "&authMechanism=MONGODB-OIDC" + + "&authMechanismProperties=ENVIRONMENT:k8s" + + client, err := mongo.Connect(options.Client().ApplyURI(uri)) + if err != nil { + panic(err) + } + +Additional Information +---------------------- + +To learn more about the concepts in this guide, see the following documentation: + +- :manual:`MongoDB Server Support for Kerberos Authentication ` +- :manual:`MongoDB Server Support for LDAP Proxy Authentication ` +- :atlas:`Authentication and Authorization with OIDC/OAuth 2.0 ` + +API Documentation +~~~~~~~~~~~~~~~~~ + +- `Credential <{+api+}/mongo/options#Credential>`__ type +- `SetAuth() <{+api+}/mongo/options#ClientOptions.SetAuth>`__ method +- `OIDCCredential <{+api+}/mongo/options#OIDCCredential>`__ type +- `OIDCCallback <{+api+}/mongo/options#OIDCCallback>`__ function diff --git a/source/security/authentication/scram.txt b/source/security/authentication/scram.txt new file mode 100644 index 00000000..53ca87a9 --- /dev/null +++ b/source/security/authentication/scram.txt @@ -0,0 +1,106 @@ +.. _golang_sha_256: +.. _golang-authentication-scram: + +============================== +SCRAM Authentication Mechanism +============================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: salt, default, code example + +Overview +-------- + +**Salted Challenge Response Authentication Mechanism (SCRAM)** is a family of +authentication mechanisms that use a challenge-response mechanism to authenticate +the user. SCRAM-SHA-256, which uses the SHA-256 algorithm to hash your password, is the +default authentication mechanism. + +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 +~~~~~~~~~~~~~~~~~ + +Each authentication mechanism contains the following placeholders: + +* ``db_username`` - Your MongoDB database username +* ``db_password`` - Your MongoDB database user's password +* ``hostname`` - Your MongoDB servers network address, accessible by + your client +* ``port`` - Your MongoDB servers port number +* ``authenticationDb`` - Your MongoDB database that contains the user's + authentication data. If you omit this option, the driver uses the + default value ``admin``. + +.. _golang-scram-sha-256: + +Specify SCRAM-SHA-256 Authentication +------------------------------------ + +``SCRAM-SHA-256`` is a salted challenge-response authentication mechanism +(SCRAM) that uses your database username and password, encrypted with the ``SHA-256`` +algorithm, to authenticate your user. ``SCRAM-SHA-256`` is the default authentication mechanism. + +To specify the default authentication mechanism, omit the +``AuthMechanism`` option: + +.. code-block:: go + + credential := options.Credential{ + AuthSource: "", + Username: "", + Password: "", + } + clientOpts := options.Client().ApplyURI("mongodb://:"). + SetAuth(credential) + + client, err := mongo.Connect(clientOpts) + +To explicitly specify the ``SCRAM-SHA-256`` authentication mechanism, assign the +``AuthMechanism`` option the value ``"SCRAM-SHA-256"``: + +.. code-block:: go + :emphasize-lines: 2 + + credential := options.Credential{ + AuthMechanism: "SCRAM-SHA-256", + AuthSource: "", + Username: "", + Password: "", + } + clientOpts := options.Client().ApplyURI("mongodb://:"). + SetAuth(credential) + + client, err := mongo.Connect(clientOpts) + +API Documentation +----------------- + +To learn more about any of the methods or types discussed on this +page, see the following API documentation: + +- `Client <{+api+}/mongo#Client>`__ +- `Credential <{+api+}/mongo/options#Credential>`__ +- `SetAuth() <{+api+}/mongo/options#ClientOptions.SetAuth>`__ +- `ClientOptions <{+api+}/mongo/options#ClientOptions>`__ diff --git a/source/security/authentication/x509.txt b/source/security/authentication/x509.txt new file mode 100644 index 00000000..b4b6d74f --- /dev/null +++ b/source/security/authentication/x509.txt @@ -0,0 +1,92 @@ +.. _golang-x509: +.. _golang-authentication-x509: + +============================== +X.509 Authentication Mechanism +============================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: certificate, code example + +Overview +-------- + +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 the :ref:`golang-tls` guide. + + For more information about X.509 certificates, see + :manual:`Use x.509 Certificates to Authenticate Clients on Self-Managed Deployments + ` in the {+mdb-server+} manual. + +Code Placeholders +~~~~~~~~~~~~~~~~~ + +The code examples on this page use the following placeholders: + +* ``hostname``: Your MongoDB servers network address, accessible by + your client +* ``port``: Your MongoDB servers port number +- ``cafile_path``: The path to your CA File for your connection string +- ``client_certificate_path``: The path to your client certificate file or the client private key file + +Specify X.509 Authentication +---------------------------- + +To specify the ``X.509`` authentication mechanism, perform the +following: + +- Assign the ``tlsCAFile`` the path to its file in the connection string +- Assign the ``tlsCertificateKeyFile`` the path to its file in the connection string +- Assign the ``AuthMechanism`` option the value ``"MONGODB-X509"`` + +The following code example shows how to specify the ``X.509`` authentication mechanism: + +.. code-block:: go + :emphasize-lines: 4-5, 7 + + caFilePath := "" + certificateKeyFilePath := "" + + uri := "mongodb://:/?tlsCAFile=%s&tlsCertificateKeyFile=%s" + uri = fmt.Sprintf(uri, caFilePath, certificateKeyFilePath) + credential := options.Credential{ + AuthMechanism: "MONGODB-X509", + } + + clientOpts := options.Client().ApplyURI(uri).SetAuth(credential) + +.. TODO + To learn more about configuring your application to use + certificates and TLS/SSL options, see + :ref:`golang-tls-ssl-guide`. + +API Documentation +----------------- + +To learn more about any of the methods or types discussed on this +page, see the following API documentation: + +- `Client <{+api+}/mongo#Client>`__ +- `Credential <{+api+}/mongo/options#Credential>`__ +- `SetAuth() <{+api+}/mongo/options#ClientOptions.SetAuth>`__ +- `ClientOptions <{+api+}/mongo/options#ClientOptions>`__