Enable TLS on a Connection在连接上启用TLS
On this page本页内容
Overview概述Enable TLS启用TLSConfigure Certificates配置证书Reference Certificates in a Client客户端中的参考证书Create a SecureContext Object to Store Certificates创建SecureContext对象以存储证书Provide Certificate Filepaths提供证书文件路径Create Buffer Objects to Store Certificates创建缓冲区对象以存储证书SecureContext ExampleSecureContext示例Additional Information附加信息API DocumentationAPI文件
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选项并提供证书以进行验证。
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 totrue
in yourMongoClientOptions
objectMongoClientOptions
对象中将tls
选项设置为true
Setting the在连接字符串中将tls
option totrue
in your connection stringtls
选项设置为true
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。
In addition to the 除了tls
client option, the driver provides additional options to configure TLS on your connection. tls
客户端选项外,驱动程序还提供了其他选项,用于在连接上配置tls
。For testing purposes, you can set the 出于测试目的,可以设置tlsAllowInvalidHostnames
, tlsAllowInvalidCertificates
, and tlsInsecure
client options.tlsAllowInvalidHostnames
、tlsAllowInvalidCertificates
和tlsInsecure
客户端选项。
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
将禁用证书和主机名验证。
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文件。
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连接所需的组件:
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 certificatesBuffer
对象以存储证书
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的详细信息,请参阅以下服务器手册文档: