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
tlsoption totruein yourMongoClientOptionsobject Setting the在连接字符串中将tlsoption totruein your connection stringtls选项设置为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 如果在连接到MongoDB时通过在连接字符串中指定+srv modification in your connection string, you enable TLS on your connection by default. +srv修改来使用DNS SRV记录,则默认情况下会在连接上启用TLS。To disable it, set the 要禁用它,请在连接字符串或tls or ssl parameter value to false in your connection string or MongoClientOptions object.MongoClientOptions对象中将tls或ssl参数值设置为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 默认情况下,Node.js驱动程序依赖于OpenSSL。在使用OpenSSL 3.0或更高版本的环境中,过时的SSL代理可能会导致不安全的旧版重新协商禁用错误。您可以通过设置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: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。出于测试目的,您可以设置tlsAllowInvalidHostnames、tlsAllowValidCertificates和tlsInsecure客户端选项。
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连接所需的组件:
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创建SecureContextobject to store certificates (Recommended)SecureContext对象以存储证书(推荐)Provide filepath strings that point to your certificates提供指向证书的文件路径字符串Create创建Bufferobjects to store certificatesBuffer对象以存储证书
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 您可以将证书的文件路径作为客户端选项,以便在使用TLS连接时检索证书。当您在connect() method on your MongoClient instance.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 您的TLS配置可能要求您在连接到MongoDB时提供证书吊销列表(CRL)。从驱动程序的6.0版本开始,您可以将CRL文件的文件路径传递给连接字符串或tlsCRLFile option in your connection string or your MongoClientOptions instance.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的更多信息,请参阅以下服务器手册文档: