Overview
Salted 挑战响应身份验证机制 (SCRAM) 是一系列身份验证机制,它们使用质询-响应机制对用户进行身份验证。 SCRAM-SHA-256 (如 RFC7677 所定义)使用 SHA-256 算法对密码进行哈希处理,是运行MongoDB v.4 0的部署的默认身份验证机制。 或更高版本。支持SCRAM-SHA- (由1 RFC5802 定义),以便与运行MongoDB v 的部署兼容。 。36
您可以使用SCRAM对MongoDB Atlas、 MongoDB Enterprise Advanced和MongoDB Community Edition进行身份验证。
提示
SCRAM 机制
代码占位符
本页上的代码示例使用以下占位符:
<db_username>:要进行身份验证的用户的MongoDB 数据库用户名。<db_password>:要进行身份验证的用户的MongoDB 数据库密码。<hostname>: MongoDB 部署的网络解决。<port>: MongoDB 部署的端口号。如果省略此参数,驱动程序将使用默认端口号 (27017)。连接MongoDB Atlas 集群时无需端口号。
要使用本页上的代码示例,请将这些占位符替换为您自己的值。
在应用程序中使用SCRAM身份验证
要使用SCRAM对MongoDB用户进行身份验证,请在连接 URI 中指定MongoDB用户名和密码以及 authSource 和 authMechanism 参数。本页上的示例使用 authSource=admin (默认身份验证数据库),并将 authMechanism设立为 SCRAM-SHA-256 或 SCRAM-SHA-1。
您可以通过以下方式进行连接:
仅使用连接 URI
使用具有在
mongocxx::options::client对象中配置的传输层安全性 (TLS) 选项的连接 URI
以下标签页显示了 TLS 和非 TLS 连接的SCRAM-SHA-256 和SCRAM -SHA-1 的示例。选择与要使用的身份验证机制和连接方法相匹配的标签页。
auto uri = mongocxx::uri("mongodb://<db_username>:<db_password>@<hostname>:<port>/?" "authSource=admin&authMechanism=SCRAM-SHA-256"); auto client = mongocxx::client(uri);
mongocxx::options::client client_options; mongocxx::options::tls tls_options; tls_options.pem_file("path/to/ca-or-client.pem"); client_options.tls_opts(tls_options); auto uri = mongocxx::uri( "mongodb://<db_username>:<db_password>@<hostname>:<port>/?" "authSource=admin&authMechanism=SCRAM-SHA-256&tls=true"); auto client = mongocxx::client(uri, client_options);
auto uri = mongocxx::uri("mongodb://<db_username>:<db_password>@<hostname>:<port>/?" "authSource=admin&authMechanism=SCRAM-SHA-1"); auto client = mongocxx::client(uri);
mongocxx::options::client client_options; mongocxx::options::tls tls_options; tls_options.pem_file("path/to/ca-or-client.pem"); client_options.tls_opts(tls_options); auto uri = mongocxx::uri( "mongodb://<db_username>:<db_password>@<hostname>:<port>/?" "authSource=admin&authMechanism=SCRAM-SHA-1&tls=true"); auto client = mongocxx::client(uri, client_options);
API 文档
要学习有关在C++驱动程序中创建 mongocxx::client对象的详情,请参阅以下API文档: