==============
Authentication
==============

The Node.js driver supports all MongoDB :manual:`authentication mechanisms </core/authentication/>` , including those only available in the MongoDB :manual:`Enterprise Edition </administration/install-enterprise/>` .

DEFAULT
-------

To use the default mechanism, either omit the authentication mechanism specification or specify ``DEFAULT`` as the mechanism in the :manual:`URI ConnectionString </reference/connection-string/>` . The driver will attempt to authenticate using the :manual:`SCRAM-SHA-256 authentication </core/security-scram/>` method if it is available on the MongoDB server. If the server does not support ``SCRAM-SHA-256``, but does support `SCRAM-SHA-1``, the driver will authenticate with ``SCRAM-SHA-1``. If neither ``SCRAM-SHA-256`` or ``SCRAM-SHA-1`` are supported on the server, the driver will authenticate using ``MONGODB-CR`` .

Include the name and password and the :manual:`authentication database </core/security-users/#user-authentication-database>` (\ ``authSource``\ ) in the connection string.

In the following example, the connection string specifies the user ``dave``\ , password ``abc123``\ , and authentication mechanism ``DEFAULT``.

.. important::
   The user and password should always be **URI** encoded using ``encodeURIComponent`` to ensure any non URI compliant user or password characters are correctly parsed.

.. code-block:: js

   const { MongoClient } = require('mongodb');

   const user = encodeURIComponent('dave');
   const password = encodeURIComponent('abc123');
   const authMechanism = 'DEFAULT';

   // Connection URL
   const url = `mongodb://${user}:${password}@localhost:27017/?authMechanism=${authMechanism}`;

   // Create a new MongoClient
   const client = new MongoClient(url);

   // Function to connect to the server
   async function run() {
     try {
       // Connect the client to the server
       await client.connect();
       console.log('Connected successfully to server');
     } finally {
       // Ensures that the client will close when you finish/error
       await client.close();
     }
   }

   // Runs your code
   run();

SCRAM-SHA-256
-------------

.. note::
   ``SCRAM-SHA-256`` is the default authentication method for MongoDB starting in version 4.0

To explicitly connect to MongoDB using :manual:`SCRAM-SHA-256 </core/security-scram/>` , specify ``SCRAM-SHA-256`` as the mechanism in the :manual:`URI ConnectionString </reference/connection-string/>` .

Include the name and password and the :manual:`authentication database </core/security-users/#user-authentication-database>` (\ ``authSource``\ ) in the connection string.

In the following example, the connection string specifies the user ``dave``\ , password ``abc123``\ , authentication mechanism ``SCRAM-SHA-256``\ , and authentication database ``myprojectdb``

.. code-block:: js

   const { MongoClient } = require('mongodb');

   // Connection URL
   const url = 'mongodb://dave:abc123@localhost:27017/?authMechanism=SCRAM-SHA-256&authSource=myprojectdb';

   // Create a new MongoClient
   const client = new MongoClient(url);

   // Function to connect to the server
   async function run() {
     try {
       // Connect the client to the server
       await client.connect();
       console.log('Connected successfully to server');
     } finally {
       // Ensures that the client will close when you finish/error
       await client.close();
     }
   }

   // Runs your code
   run();

SCRAM-SHA-1
-----------

.. note::
   ``SCRAM-SHA-1`` is the default authentication method for MongoDB versions 3.0, 3.2, 3.4, and 3.6.

To explicitly connect to MongoDB using :manual:`SCRAM-SHA-1 </core/security-scram/>` , specify ``SCRAM-SHA-1`` as the mechanism in the :manual:`URI ConnectionString </reference/connection-string/>` .

Include the name and password and the :manual:`authentication database </core/security-users/#user-authentication-database>` (\ ``authSource``\ ) in the connection string.

In the following example, the connection string specifies the user ``dave``\ , password ``abc123``\ , authentication mechanism ``SCRAM-SHA-1``\ , and authentication database ``myprojectdb``

.. code-block:: js

   const { MongoClient } = require('mongodb');

   // Connection URL
   const url = 'mongodb://dave:abc123@localhost:27017/?authMechanism=SCRAM-SHA-1&authSource=myprojectdb';

   // Create a new MongoClient
   const client = new MongoClient(url);

   // Function to connect to the server
   async function run() {
     try {
       // Connect the client to the server
       await client.connect();
       console.log('Connected successfully to server');
     } finally {
       // Ensures that the client will close when you finish/error
       await client.close();
     }
   }

   // Runs your code
   run();

MONGODB-CR
----------

.. warning::
   MONGODB-CR was deprecated starting in MongoDB 3.6, and is no longer supported as of MongoDB 4.0


To explicitly connect to MongoDB using ``MONGODB-CR`` , specify ``MONGODB-CR`` as the mechanism in the :manual:`URI ConnectionString </reference/connection-string/>` .

Include the name and password and the :manual:`authentication database </core/security-users/#user-authentication-database>` (\ ``authSource``\ ) in the connection string.

In the following example, the connection string specifies the user ``dave``\ , password ``abc123``\ , authentication mechanism ``MONGODB-CR``\ , and authentication database ``myprojectdb``.

.. code-block:: js

   const { MongoClient } = require('mongodb');

   // Connection URL
   const url = 'mongodb://dave:abc123@localhost:27017/?authMechanism=MONGODB-CR&authSource=myprojectdb';

   // Create a new MongoClient
   const client = new MongoClient(url);

   // Function to connect to the server
   async function run() {
     try {
       // Connect the client to the server
       await client.connect();
       console.log('Connected successfully to server');
     } finally {
       // Ensures that the client will close when you finish/error
       await client.close();
     }
   }

   // Runs your code
   run();

.. important::
   If you have :manual:`upgraded the authentication schema </release-notes/3.0-scram/>` from ``MONGODB-CR`` to ``SCRAM-SHA-1``\ , ``MONGODB-CR`` credentials will fail to authenticate.

X509
----

With  :manual:`X.509 </core/security-x.509>` mechanism, MongoDB uses the X.509 certificate presented during TLS negotiation to authenticate a user whose name is derived from the distinguished name of the X.509 certificate.

X.509 authentication requires the use of TLS connections with certificate validation and is available in MongoDB 2.6 and newer.

To connect using the X.509 authentication mechanism, specify ``MONGODB-X509`` as the mechanism in the :manual:`URI ConnectionString </reference/connection-string/>` , ``tls=true``\ , and the username. Use ``enodeURIComponent`` to encode the username string.

In addition to the connection string, pass to the new ``MongoClient`` a connections options for the ``server`` with the X.509 certificate and other :doc:`TLS/SSL connections </tutorials/connect/tls>` options.

.. code-block:: js

   const { MongoClient } = require('mongodb');
   const fs = require('fs');

   // User name
   const userName = encodeURIComponent('CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US');
   const url = `mongodb://${userName}:${password}@server:27017?authMechanism=MONGODB-X509&tls=true`;

   // Create a new MongoClient
   const client = new MongoClient(url, {
     tlsCertificateKeyFile: `${__dirname}/certs/x509/client.pem`,
   });

   // Function to connect to the server
   async function run() {
     try {
       // Connect the client to the server
       await client.connect();
       console.log('Connected successfully to server');
     } finally {
       // Ensures that the client will close when you finish/error
       await client.close();
     }
   }

   // Runs your code
   run();

For more information on connecting to MongoDB instance, replica set, and sharded cluster with TLS/SSL options, see :doc:`TLS/SSL connections </tutorials/connect/tls>` .

For more information, refer to the MongoDB manual
:manual:`X.509 tutorial </tutorial/configure-x509-client-authentication/#add-x-509-certificate-subject-as-a-user>` for more information about determining the subject name from the certificate.

Kerberos (GSSAPI/SSPI)
----------------------

`MongoDB Enterprise <http://www.mongodb.com/products/mongodb-enterprise>`_  supports proxy authentication through a Kerberos service. The Node.js driver supports Kerberos on UNIX via the MIT Kerberos library and on Windows via the SSPI API.

To connect using the GSSAPI authentication mechanism, specify ``authMechanism=GSSAPI`` as the mechanism in the :manual:`URI ConnectionString </reference/connection-string/>` . Specify the user principal and the service name in the connection string.  Use ``enodeURIComponent`` to encode the user principal string.

The following example connects to MongoDB using Kerberos for UNIX.

.. code-block:: js

   const { MongoClient } = require('mongodb');

   // KDC Server
   const server = 'mongo-server.example.com';
   const principal = 'drivers@KERBEROS.EXAMPLE.COM';
   const urlEncodedPrincipal = encodeURIComponent(principal);

   const url = `mongodb://${urlEncodedPrincipal}@${server}/?authMechanism=GSSAPI&gssapiServiceName=mongodb`;

   const client = new MongoClient(url);

   // Function to connect to the server
   async function run() {
     try {
       // Connect the client to the server
       await client.connect();
       console.log('Connected successfully to server');
     } finally {
       // Ensures that the client will close when you finish/error
       await client.close();
     }
   }

   // Runs your code
   run();

.. note::
   The method refers to the ``GSSAPI`` authentication mechanism instead of ``Kerberos`` because technically the driver authenticates via the :rfc:`GSSAPI <4752>` SASL mechanism.

LDAP (PLAIN)
------------

`MongoDB Enterprise <http://www.mongodb.com/products/mongodb-enterprise>`_ supports proxy authentication through a Lightweight Directory Access Protocol (LDAP) service.

To connect using the LDAP authentication mechanism, specify ``authMechanism=PLAIN`` as the mechanism in the :manual:`URI ConnectionString </reference/connection-string/>` .

.. code-block:: js

   const { MongoClient } = require('mongodb');

   // LDAP Server
   const server = 'ldap.example.com';
   const user = 'ldap-user';
   const pass = 'ldap-password';

   // Url
   const url = `mongodb://${user}:${pass}@${server}?authMechanism=PLAIN&maxPoolSize=1`;

   // Client
   const client = new MongoClient(url);

   // Function to connect to the server
   async function run() {
     try {
       // Connect the client to the server
       await client.connect();
       console.log('Connected successfully to server');
     } finally {
       // Ensures that the client will close when you finish/error
       await client.close();
     }
   }

   // Runs your code
   run();

.. note::
   The method refers to the ``PLAIN`` authentication mechanism instead of ``LDAP`` because technically the driver authenticates via the :rfc:`PLAIN <4616>` SASL mechanism.
