身份验证机制
在本指南中,您可以找到使用MongoDB社区版中提供的每种身份验证机制连接到MongoDB的示例代码默认
、SCRAM-SHA-256
、SCRAM-SHA-1
、MONGODB-CR
、MONGODB-AWS
和 X.509
。
默认
默认
身份验证机制是一个后备设置,指示驱动程序与服务器协商以下优先级顺序中服务器支持的第一个身份验证机制
SCRAM-SHA-256
SCRAM-SHA-1
MONGODB-CR
如果指定了默认
选项,驱动程序首先尝试使用SCRAM-SHA-256
进行身份验证。如果MongoDB实例的版本不支持该机制,驱动程序将尝试使用SCRAM-SHA-1
进行身份验证。如果实例也不支持该机制,驱动程序将尝试使用MONGODB-CR
进行身份验证。
您可以通过在以下设置中将authMechanism
参数设置为默认
来指定此身份验证机制连接字符串,或者省略该参数,因为它是默认值。同时,请包括以下代码中所示的用户名和密码。
重要
始终使用encodeURIComponent
方法对用户名和密码进行编码,以确保它们被正确解析。
const { MongoClient } = require("mongodb"); // Replace the following with values for your environment. const username = encodeURIComponent("<db_username>"); const password = encodeURIComponent("<db_password>"); const clusterUrl = "<MongoDB cluster url>"; const authMechanism = "DEFAULT"; // Replace the following with your MongoDB deployment's connection string. const uri = `mongodb+srv://${username}:${password}@${clusterUrl}/?authMechanism=${authMechanism}`; // Create a new MongoClient const client = new MongoClient(uri); // Function to connect to the server async function run() { try { // Establish and verify connection await client.db("admin").command({ ping: 1 }); console.log("Connected successfully to server"); } finally { // Ensures that the client will close when you finish/error await client.close(); } } run().catch(console.dir);
有关MongoDB支持的挑战-响应(CR)和加盐挑战-响应身份验证机制(SCRAM)的更多信息,请参阅手册中的SCRAM
部分。
SCRAM-SHA-256
注意
SCRAM-SHA-256
是从 MongoDB 版本 4.0 开始的默认认证方法。
SCRAM-SHA-256
是一种加盐的挑战-响应认证机制 (SCRAM),它使用 SHA-256
算法加密您的用户名和密码以认证您的用户。
您可以通过在连接字符串中设置 authMechanism
为值 SCRAM-SHA-256
来指定此认证机制,如下面的示例代码所示。
重要
始终使用encodeURIComponent
方法对用户名和密码进行编码,以确保它们被正确解析。
const { MongoClient } = require("mongodb"); // Replace the following with values for your environment. const username = encodeURIComponent("<db_username>"); const password = encodeURIComponent("<db_password>"); const clusterUrl = "<MongoDB cluster url>"; const authMechanism = "SCRAM-SHA-256"; // Replace the following with your MongoDB deployment's connection string. const uri = `mongodb+srv://${username}:${password}@${clusterUrl}/?authMechanism=${authMechanism}`; // Create a new MongoClient const client = new MongoClient(uri); // Function to connect to the server async function run() { try { // Establish and verify connection await client.db("admin").command({ ping: 1 }); console.log("Connected successfully to server"); } finally { // Ensures that the client will close when you finish/error await client.close(); } } run().catch(console.dir);
SCRAM-SHA-1
注意
SCRAM-SHA-1
是 MongoDB 版本 3.0、3.2、3.4 和 3.6 的默认认证方法。
SCRAM-SHA-1
是一种加盐的挑战-响应机制 (SCRAM),它使用 SHA-1
算法加密您的用户名和密码以认证您的用户。
您可以通过在连接字符串中设置 authMechanism
参数为值 SCRAM-SHA-1
来指定此认证机制,如下面的示例代码所示。
重要
始终使用encodeURIComponent
方法对用户名和密码进行编码,以确保它们被正确解析。
const { MongoClient } = require("mongodb"); // Replace the following with values for your environment. const username = encodeURIComponent("<db_username>"); const password = encodeURIComponent("<db_password>"); const clusterUrl = "<MongoDB cluster url>"; const authMechanism = "SCRAM-SHA-1"; // Replace the following with your MongoDB deployment's connection string. const uri = `mongodb+srv://${username}:${password}@${clusterUrl}/?authMechanism=${authMechanism}`; // Create a new MongoClient const client = new MongoClient(uri); // Function to connect to the server async function run() { try { // Establish and verify connection await client.db("admin").command({ ping: 1 }); console.log("Connected successfully to server"); } finally { // Ensures that the client will close when you finish/error await client.close(); } } run().catch(console.dir);
MONGODB-CR
警告
MONGODB-CR自MongoDB 3.6开始已弃用,MongoDB 4.0及以后版本不再支持。
MONGODB-CR
是一种挑战-响应身份验证机制,使用您的用户名和密码来验证您的用户。
您可以通过将连接字符串中的authMechanism
参数设置为MONGODB-CR
来指定此选项,如下面的示例代码所示。
重要
始终使用encodeURIComponent
方法对用户名和密码进行编码,以确保它们被正确解析。
const { MongoClient } = require("mongodb"); // Replace the following with values for your environment. const username = encodeURIComponent("<db_username>"); const password = encodeURIComponent("<db_password>"); const clusterUrl = "<MongoDB cluster url>"; // Replace the following with your MongoDB deployment's connection string. const uri = `mongodb+srv://${username}:${password}@${clusterUrl}/?authMechanism=${authMechanism}&tls=true&tlsCertificateKeyFile=${clientPEMFile}`; // Create a new MongoClient const client = new MongoClient(uri); // Function to connect to the server async function run() { try { // Establish and verify connection await client.db("admin").command({ ping: 1 }); console.log("Connected successfully to server"); } finally { // Ensures that the client will close when you finish/error await client.close(); } } run().catch(console.dir);
重要
如果您已将身份验证模式从MONGODB-CR升级到SCRAM,则任何MONGODB-CR
用户身份验证请求都将失败。
MONGODB-AWS
注意
MONGODB-AWS身份验证机制仅在MongoDB 4.4及以后版本中可用。
《MONGODB-AWS》认证机制使用您的Amazon Web Services身份和访问管理(AWS IAM)凭证来认证您的用户。如果您还没有AWS签名库,可以使用以下npm
命令来安装它
npm install aws4
要连接到已启用MONGODB-AWS
认证的MongoDB实例,请指定MONGODB-AWS
认证机制。
驱动程序会按照以下顺序检查您的凭证:
连接字符串
环境变量
Web身份令牌文件
在
AWS_CONTAINER_CREDENTIALS_RELATIVE_URI
中指定的AWS ECS端点AWS EC2端点。更多信息,请参阅IAM Roles for Tasks。
重要
驱动程序仅从它检测到的第一个方法中读取凭证,顺序与前面列表中给出的顺序相同。例如,如果您在连接字符串中指定了您的AWS凭证,则驱动程序将忽略您在环境变量中指定的任何凭证。
要使用连接字符串连接到您的MongoDB实例,在尝试连接时将您的AWS_ACCESS_KEY_ID
和AWS_SECRET_ACCESS_KEY
凭证传递给驱动程序。如果您的AWS登录需要会话令牌,请包括您的AWS_SESSION_TOKEN
。
以下代码显示了使用连接字符串指定MONGODB-AWS
认证机制和凭证的示例
重要
始终使用encodeURIComponent
方法对用户名和证书文件路径进行URI编码,以确保它们被正确解析。
const { MongoClient } = require("mongodb"); // Replace the following with values for your environment. const accessKeyId = encodeURIComponent("<AWS_ACCESS_KEY_ID>"); const secretAccessKey = encodeURIComponent("<AWS_SECRET_ACCESS_KEY>"); const clusterUrl = "<MongoDB cluster url>"; const authMechanism = "MONGODB-AWS"; let uri = `mongodb+srv://${accessKeyId}:${secretAccessKey}@${clusterUrl}/?authSource=%24external&authMechanism=${authMechanism}`; // Uncomment the following lines if your AWS authentication setup requires a session token. // const sessionToken = encodeURIComponent("<AWS_SESSION_TOKEN>"); // uri = uri.concat(`&authMechanismProperties=AWS_SESSION_TOKEN:${sessionToken}`); // Create a new MongoClient. const client = new MongoClient(uri); async function run() { try { // Establish and verify connection. await client.db("admin").command({ ping: 1 }); console.log("Connected successfully to server."); } finally { // Ensure that the client closes when it finishes/errors. await client.close(); } } run().catch(console.dir);
要使用存储在环境变量中的AWS凭证对MongoDB实例进行认证,请使用shell设置以下变量
export AWS_ACCESS_KEY_ID=<awsKeyId> export AWS_SECRET_ACCESS_KEY=<awsSecretKey> export AWS_SESSION_TOKEN=<awsSessionToken>
注意
如果该角色不需要AWS会话令牌,请忽略包含AWS_SESSION_TOKEN
的行。
设置完前面的环境变量后,如以下示例所示,在您的连接字符串中指定MONGODB-AWS
身份验证机制
const { MongoClient } = require("mongodb"); // Remember to specify your AWS credentials in environment variables. const clusterUrl = "<MongoDB deployment url>"; const authMechanism = "MONGODB-AWS"; let uri = `mongodb+srv://${clusterUrl}/?authSource=%24external&authMechanism=${authMechanism}`; // Create a new MongoClient. const client = new MongoClient(uri); async function run() { try { // Establish and verify connection. await client.db("admin").command({ ping: 1 }); console.log("Connected successfully to server."); } finally { // Ensure that the client closes when it finishes/errors. await client.close(); } } run().catch(console.dir);
您可以使用从Web身份提供者获得的OpenID Connect (OIDC)令牌来验证Amazon Elastic Kubernetes Service (EKS)或其他服务。
要使用您的OIDC令牌进行验证,您必须首先安装@aws-sdk/credential-providers。您可以使用以下npm
命令安装此依赖项
npm install @aws-sdk/credential-providers
接下来,创建一个包含您的OIDC令牌的文件。然后使用以下示例中的shell将此文件的绝对路径设置为环境变量
export AWS_WEB_IDENTITY_TOKEN_FILE=<absolute path to file containing your OIDC token>
设置完前面的环境变量后,如以下示例所示,在您的连接字符串中指定MONGODB-AWS
身份验证机制
const { MongoClient } = require("mongodb"); // Remember to specify your AWS credentials in environment variables. const clusterUrl = "<MongoDB deployment url>"; const authMechanism = "MONGODB-AWS"; let uri = `mongodb+srv://${clusterUrl}/?authSource=%24external&authMechanism=${authMechanism}`; // Create a new MongoClient. const client = new MongoClient(uri); async function run() { try { // Establish and verify connection. await client.db("admin").command({ ping: 1 }); console.log("Connected successfully to server."); } finally { // Ensure that the client closes when it finishes/errors. await client.close(); } } run().catch(console.dir);
重要
AWS凭证的检索
从版本4.11开始,当您安装可选的aws-sdk/credential-providers
依赖项时,驱动程序会使用AWS SDK从环境检索凭证。因此,如果您有一个共享的AWS凭证文件或配置文件,驱动程序将默认使用这些凭证。
您可以通过执行以下操作之一来覆盖此行为
在您的shell中设置
AWS_SHARED_CREDENTIALS_FILE
变量,将其指向您的凭证文件。在您的应用程序中设置等效的环境变量,将其指向您的凭证文件。
为您的MongoDB凭证创建一个AWS配置文件,并将
AWS_PROFILE
环境变量设置为该配置文件名。
X.509
注意
X.509身份验证机制仅在MongoDB 2.6及以后的版本中可用。
使用X.509证书通过从客户端证书检索区分名称(DN)进行认证的X.509认证机制与TLS进行认证。
您可以通过设置以下连接字符串参数来指定此认证机制:
将
authMechanism
参数设置为MONGODB-X509
将
tls
参数设置为true
将客户端证书文件的路径作为连接URI的参数传递给tlsCertificateKeyFile
。
重要
始终使用encodeURIComponent
方法对证书文件路径进行URL编码,以确保它被正确解析。
const { MongoClient } = require("mongodb"); // Replace the following with values for your environment. const clusterUrl = "<MongoDB cluster url>"; const clientPEMFile = encodeURIComponent("<path to the client pem certificate file>"); const authMechanism = "MONGODB-X509"; // Replace the following with your MongoDB deployment's connection string. const uri = `mongodb+srv://${clusterUrl}/?authMechanism=${authMechanism}&tls=true&tlsCertificateKeyFile=${clientPEMFile}`; // Create a new MongoClient const client = new MongoClient(uri); // Function to connect to the server async function run() { try { // Establish and verify connection await client.db("admin").command({ ping: 1 }); console.log("Connected successfully to server"); } finally { // Ensures that the client will close when you finish/error await client.close(); } } run().catch(console.dir);
提示
有关在连接上启用TLS的更多信息,请参阅在连接上启用TLS.
TLS选项
以下表格描述了您可以在连接URI中设置的TLS选项。
参数名称 | 类型 | 默认值 | 描述 |
---|---|---|---|
tls | 布尔值 | false | 指定是否在连接上启用TLS。 |
tlsInsecure | 布尔值 | false | 指定是否允许无效证书和不匹配的主机名。当设置为 true 时,这相当于将tlsAllowInvalidCertificates 和tlsAllowInvalidHostnames 设置为true 。 |
tlsCAFile | 字符串 | 包含用于TLS连接的单个或一组受信任证书权威机构文件的路径。 | |
tlsCertificateKeyFile | 字符串 | 客户端证书文件或客户端私钥文件的路径。如果两者都必需,则必须将它们连接到单个文件中。 | |
tlsCertificateKeyFilePassword | 缓冲区或字符串 | 包含解密客户端私钥的密码的字符串或缓冲区。 | |
tlsAllowInvalidCertificates | 布尔值 | false | 指定是否允许使用无效证书进行连接。 |
tlsAllowInvalidHostnames | 布尔值 | false | 指定当服务器主机名和TLS证书主机名不匹配时,驱动程序是否引发错误。 |