Docs Home / Node.js Driver

Enable TLS on a Connection在连接上启用TLS

Overview概述

In this guide, you can learn how to connect to MongoDB instances with the TLS security protocol.在本指南中,您可以学习如何使用TLS安全协议连接到MongoDB实例。

To configure your connection to use TLS, enable the TLS option and provide your certificates for validation.要将连接配置为使用TLS,请启用TLS选项并提供证书以供验证。

Tip

To learn more about TLS, see the Wikipedia entry on Transport Layer Security.要了解有关TLS的更多信息,请参阅维基百科中关于传输层安全的条目。

Enable TLS启用TLS

You can enable TLS on a connection to your MongoDB instance in the following ways:您可以通过以下方式在与MongoDB实例的连接上启用TLS:

  • Setting the tls option to true in your MongoClientOptions object
  • Setting the tls option to true in your connection string在连接字符串中将tls选项设置为true
MongoClientOptions

A MongoClient instance can connect with TLS if you set tls to true in your MongoClientOptions object:如果在MongoClientOptions对象中将TLS设置为true,则MongoClient实例可以与TLS连接:

const client = new MongoClient(uri, { tls: true });
Connection String连接字符串

A MongoClient instance can connect with TLS if you set the tls option to true in your connection string:如果您在连接字符串中将tls选项设置为true,则MongoClient实例可以与TLS连接:

const uri = "mongodb://<hostname>:<port>?tls=true";
const client = new MongoClient(uri, myClientSettings);

Note

If you use a DNS SRV record when connecting to MongoDB by specifying the +srv modification in your connection string, you enable TLS on your connection by default. 如果在连接到MongoDB时通过在连接字符串中指定+srv修改来使用DNS SRV记录,则默认情况下会在连接上启用TLS。To disable it, set the tls or ssl parameter value to false in your connection string or MongoClientOptions object.要禁用它,请在连接字符串或MongoClientOptions对象中将tlsssl参数值设置为false

To learn more about connection behavior when you use a DNS seedlist, see the SRV Connection Format section in the Server manual.要了解有关使用DNS种子列表时的连接行为的更多信息,请参阅服务器手册中的SRV连接格式部分。

Note

Workaround for an "unsafe legacy renegotiation disabled" Error解决“禁用不安全的遗留重新协商”错误

The Node.js driver depends on OpenSSL by default. Outdated SSL proxies can cause an unsafe legacy renegotiation disabled error in environments using OpenSSL 3.0 or later. You can resolve this error by setting the SSL_OP_LEGACY_SERVER_CONNECT option, as shown in the following example:默认情况下,Node.js驱动程序依赖于OpenSSL。在使用OpenSSL 3.0或更高版本的环境中,过时的SSL代理可能会导致不安全的旧版重新协商禁用错误。您可以通过设置SSL_OP_LEGACY_SERVER_CONNECT选项来解决此错误,如下例所示:

import { MongoClient } from 'mongodb';
import crypto from 'crypto';

const client = new MongoClient("mongodb+srv://...", {
secureContext: {
secureOptions: crypto.constants.SSL_OP_LEGACY_SERVER_CONNECT
}
});

In addition to the tls client option, the driver provides more options to configure TLS on your connection. For testing purposes, you can set the tlsAllowInvalidHostnames, tlsAllowInvalidCertificates, and tlsInsecure client options.除了tls客户端选项外,驱动程序还提供了更多选项来配置连接上的tls。出于测试目的,您可以设置tlsAllowInvalidHostnamestlsAllowValidCertificatestlsInsecure客户端选项。

Setting the tlsAllowInvalidHostnames option to true disables hostname verification, and setting the tlsAllowInvalidCertificates to true disables certificate validation. Setting the tlsInsecure option to true disables both certificate and hostname validation.tlsAllowInvalidHostnames选项设置为true会禁用主机名验证,将tlsAlowInvalidCertificates设置为true则会禁用证书验证。将tlsInsecure选项设置为true将禁用证书和主机名验证。

Warning

Specifying any of these options in a production environment makes your application insecure and potentially vulnerable to expired certificates and to foreign processes posing as valid client instances.在生产环境中指定这些选项中的任何一个都会使您的应用程序不安全,并可能容易受到过期证书和冒充有效客户端实例的外部进程的攻击。

For a full list of client options, see Specify Connection Options.有关客户端选项的完整列表,请参阅指定连接选项

Configure Certificates配置证书

To successfully initiate a TLS request, an application must prove its identity by referencing cryptographic certificates. To connect to MongoDB with TLS, your certificates must be stored as PEM files.为了成功发起TLS请求,应用程序必须通过引用加密证书来证明其身份。要使用TLS连接到MongoDB,您的证书必须存储为PEM文件。

Important

For production use, we recommend that your MongoDB deployment use valid certificates generated and signed by the same certificate authority. For testing, you can use self-signed certificates.对于生产使用,我们建议您的MongoDB部署使用由同一证书颁发机构生成和签名的有效证书。对于测试,您可以使用自签名证书。

The following list describes the components required to establish a connection with TLS:以下列表描述了建立TLS连接所需的组件:

TLS ComponentTLS组件Description描述
Certificate Authority (CA)证书颁发机构(CA)One or more certificate authorities to trust when making a TLS connection.建立TLS连接时要信任的一个或多个证书颁发机构。
Client Certificate客户端证书A digital certificate and key that allow the server to verify the identity of your application to establish an encrypted network connection.一种数字证书和键,允许服务器验证应用程序的身份,以建立加密的网络连接。
Certificate Key证书键The client certificate private key file. This key is often included within the certificate file itself.客户端证书私钥文件。此键通常包含在证书文件本身中。
Passphrase口令短语The password to decrypt the private client key if it is encrypted.解密私有客户端键(如果已加密)的密码。

Tip

To learn more about the PEM format, see the Wikipedia entry on Privacy-Enhanced Mail.要了解有关PEM格式的更多信息,请参阅维基百科中关于隐私增强邮件的条目。

Reference Certificates in a Client客户端中的参考证书

You must reference your certificates in your MongoClientOptions object so that the server can validate them before the client connects. You can reference your certificates in the following ways:您必须在MongoClientOptions对象中引用您的证书,以便服务器可以在客户端连接之前验证它们。您可以通过以下方式引用您的证书:

  • Create a SecureContext object to store certificates (Recommended)创建SecureContext对象以存储证书(推荐)
  • Provide filepath strings that point to your certificates提供指向证书的文件路径字符串
  • Create Buffer objects to store certificates创建Buffer对象以存储证书

Create a SecureContext Object to Store Certificates创建一个SecureContext对象来存储证书

We recommend that you use the secureContext option to configure your TLS connection. SecureContext objects are native to Node.js and allow you to keep all your TLS options in a single reusable object.我们建议您使用secureContext选项来配置TLS连接。SecureContext对象是Node.js的原生对象,允许您将所有TLS选项保存在一个可重用的对象中。

To create a SecureContext object, import the createSecureContext() method from the tls module. 要创建SecureContext对象,请从tls模块导入createSecureContext()方法。Next, call the createSecureContext() method and pass the contents of your certificates in the options parameter. 接下来,调用createSecureContext()方法,并在options参数中传递证书的内容。This method returns a SecureContext object that you can use in your MongoClientOptions object.此方法返回一个SecureContext对象,您可以在MongoClientOptions对象中使用该对象。

The following code shows how to create a SecureContext object and pass it to your client:以下代码显示了如何创建SecureContext对象并将其传递给客户端:

// Create a SecureContext object创建SecureContext对象
const secureContext = tls.createSecureContext({
ca: fs.readFileSync(`<path to CA certificate>`),
cert: fs.readFileSync(`<path to public client certificate>`),
key: fs.readFileSync(`<path to private client key>`),
});

// Pass the SecureContext as a client option将SecureContext作为客户端选项传递
const client = new MongoClient(uri, { tls: true, secureContext });

To learn more about the createSecureContext() method and the tls package, see the Node.js TLS API documentation.要了解有关createSecureContext()方法和tls包的更多信息,请参阅Node.js-tls API文档

For a runnable example that uses a SecureContext object, see the SecureContext Example.有关使用SecureContext对象的可运行示例,请参阅SecureContext示例

Provide Certificate Filepaths提供证书文件路径

You can include the filepaths for your certificates as client options to retrieve your certificates while connecting with TLS. The driver reads these files when you call the connect() method on your MongoClient instance.您可以将证书的文件路径作为客户端选项,以便在使用TLS连接时检索证书。当您在MongoClient实例上调用connect()方法时,驱动程序会读取这些文件。

The following code shows how to provide certificate filepaths as options in your MongoClient:以下代码显示了如何在MongoClient中提供证书文件路径作为选项:

// Pass filepaths as client options将文件路径作为客户端选项传递
const client = new MongoClient(uri, {
tls: true,
tlsCAFile: `<path to CA certificate>`,
tlsCertificateKeyFile: `<path to private client key>`,
});

Note

CRL FilesCRL文件

Your TLS configuration might require that you present a certificate revocation list (CRL) when connecting to MongoDB. Starting in version 6.0 of the driver, you can pass the filepath of your CRL file to the tlsCRLFile option in your connection string or your MongoClientOptions instance.您的TLS配置可能要求您在连接到MongoDB时提供证书吊销列表(CRL)。从驱动程序的6.0版本开始,您可以将CRL文件的文件路径传递给连接字符串或MongoClientOptions实例中的tlsCRLFile选项。

Create Buffer Objects to Store Certificates创建缓冲区对象以存储证书

You can pass the contents of your certificate files as Buffer objects in your client options to connect with TLS.您可以在客户端选项中将证书文件的内容作为Buffer对象传递,以与TLS连接。

The following code shows how to read the contents of your certificate files and pass the resulting Buffer objects as options in your MongoClient:以下代码显示了如何读取证书文件的内容,并将生成的Buffer对象作为MongoClient中的选项传递:

// Read file contents读取文件内容
const ca = fs.readFileSync(`<path to CA certificate>`);
const cert = fs.readFileSync(`<path to public client certificate>`);
const key = fs.readFileSync(`<path to private client key>`);

// Pass Buffers as client options将缓冲区作为客户端选项传递
const client = new MongoClient(uri, { tls: true, ca, cert, key });

SecureContext Example安全上下文示例

This example shows how to create a SecureContext object and a MongoClient instance that includes TLS options. The example connects to MongoDB and executes a find query:此示例显示了如何创建SecureContext对象和包含TLS选项的MongoClient实例。该示例连接到MongoDB并执行查找查询:

import { MongoClient } from "mongodb";
import * as fs from "fs";
import * as tls from "tls";

// Replace the uri string with your connection string.将uri字符串替换为连接字符串。
const uri = "<connection uri>";

// Replace the filepaths with your certificate filepaths.将文件路径替换为证书文件路径。
const secureContext = tls.createSecureContext({
ca: fs.readFileSync(`<path to CA certificate>`),
cert: fs.readFileSync(`<path to public client certificate>`),
key: fs.readFileSync(`<path to private client key>`),
});

// Create a client with the secureContext option使用secureContext选项创建客户端
const client = new MongoClient(uri, { tls: true, secureContext });

async function run() {
try {
const db = client.db("myDB");
const myColl = db.collection("myColl");
const doc = await myColl.findOne({});
console.log(doc);
} finally {
await client.close();
}
}
run().catch(console.dir);

Additional Information附加信息

For more information about enabling TLS on a connection, see the following Server manual documentation:有关在连接上启用TLS的更多信息,请参阅以下服务器手册文档:

API Documentation文档