Docs HomeNode.js

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 objectMongoClientOptions对象中将tls选项设置为true
  • Setting the tls option to true in your connection string在连接字符串中将tls选项设置为true
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。

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

Setting the tlsAllowInvalidHostnames option to true disables hostname verification, and setting the tlsAllowInvalidCertificates to true disables certificate validation. tlsAllowInvalidHostnames选项设置为true将禁用主机名验证,将tlsAlowInvalidCertificates设置为true则禁用证书验证。Setting the tlsInsecure option to true disables both certificate and hostname validation.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 Connection Options.有关客户端选项的完整列表,请参阅连接选项

Configure Certificates配置证书

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

Important

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

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

TLS ComponentTLS组件Description描述
Certificate Authority证书颁发机构 (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. 您必须在MongoClientOptions对象中引用证书,以便服务器能够在客户端连接之前对其进行验证。You can reference your certificates in the following ways:您可以通过以下方式引用证书:

  • 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选项来配置TLS连接。SecureContext objects are native to Node.js and allow you to keep all your TLS options in a single reusable object.对象是Node.js的原生对象,允许您将所有TLS选项保留在一个可重用的对象中。

To create a SecureContext object, import the createSecureContext() method from the tls module. 要创建SecureContext对象,请从tls模块导入createSecureContect()方法。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对象的可运行示例,请参阅SecureContect示例

Provide Certificate Filepaths提供证书文件路径

You can include the filepaths for your certificates as client options to retrieve your certificates while connecting with TLS.您可以将证书的文件路径作为客户端选项,以便在使用TLS连接时检索证书。

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>`,
tlsCertificateFile: `<path to public client certificate>`,
tlsCertificateKeyFile: `<path to private client key>`,
});

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 ExampleSecureContext示例

This example shows how to create a SecureContext object and a MongoClient instance that includes TLS options. 这个例子展示了如何创建一个SecureContext对象和一个包含TLS选项的MongoClient实例。The example connects to MongoDB and executes a find query:该示例连接到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 DocumentationAPI文件