Skip to main content

SSL

作为连接选项的一部分,你可以指定 ssl 对象属性或包含 SSL 配置文件内容的字符串(已弃用)。

¥As part of the connection options, you can specify the ssl object property or a string containing the SSL profile content (deprecated).

ssl?: string | SslOptions;

查看 SslOptions 的完整列表,其格式与 tls.createSecureContext 相同。

¥See full list of SslOptions, which are in the same format as tls.createSecureContext.

SSL 选项

¥SSL Options

要在不手动提供证书的情况下启用 SSL 并假设它们已被主机信任,你可以指定一个空对象,例如:

¥To enable SSL without manually providing certificates and assuming they are already trusted by the host machine, you can specify an empty object, for example:

const connection = await mysql.createConnection({
host: 'localhost',
ssl: {},
});

你还可以将自定义证书指定为单个字符串或字符串数​​组。请注意,参数需要证书的字符串,而不是证书的文件名:

¥You can also specify custom certificate(s) as an individual string or array of strings. Please note the arguments expect a string of the certificate, not a file name to the certificate:

import fs from 'node:fs';

const connection = await mysql.createConnection({
host: 'localhost',
ssl: {
ca: fs.readFileSync(__dirname + '/mysql-ca.crt'),
},
});

从环境变量读取证书时,建议用适当的换行符替换转义的 \n 字符,例如:

¥When a certificate is read from an environment variable, it's recommended to replace escaped \n characters with proper new line characters, for example:

const connection = await mysql.createConnection({
host: 'localhost',
ssl: {
ca: process.env.DB_SSL_CA?.replace(/\\n/gm, '\n'),
},
});

SSL 证书包

¥SSL Certificate Bundle

或者,你可以使用包含 CA 证书的包。例如,对于 Amazon RDS,你可以使用:

¥Alternatively, you can use a bundle with CA certificates. For example for Amazon RDS you could use:

import awsCaBundle from 'aws-ssl-profiles';

const connection = await mysql.createConnection({
host: 'db.id.ap-southeast-2.rds.amazonaws.com',
ssl: awsCaBundle,
});

有关详细说明,请遵循 aws-ssl-profiles 文档。

¥For detailed instructions, please follow aws-ssl-profiles documentation.

SSL 配置文件(已弃用)

¥SSL Profile (deprecated)

还有一个弃用的选项,允许指定包含 SSL 配置文件名称的字符串:

¥There is also a deprecated option allowing to specify a string containing name of SSL profile:

const connection = await mysql.createConnection({
host: 'localhost',
ssl: 'Amazon RDS',
});

软件包中包含以下配置文件:

¥Following profiles are included in the package:

忽略未经授权的 SSL 错误

¥Ignoring Unauthorized SSL Errors

你还可以连接到 MySQL 服务器,而无需提供适当的 CA 来信任。由于不安全,强烈建议不要这样做。

¥You can also connect to a MySQL server without providing an appropriate CA to trust. This is highly discouraged as being insecure.

const connection = await mysql.createConnection({
host: 'localhost',
ssl: {
// Beware, set `rejectUnauthorized` as `false` is strongly discouraged for security reasons:
rejectUnauthorized: false,
},
});