Overview
在 X.509 身份验证机制中,服务器和客户端使用 TLS协议交换 X.509 公钥证书。您可以使用此机制对MongoDB Atlas、 MongoDB Enterprise Advanced和MongoDB Community Edition进行身份验证。
代码占位符
本页上的代码示例使用以下占位符:
+srv: Include this option in your connection string prefix only if you are connecting to a MongoDB Atlas cluster. To learn more about the+srvoption, see Connection String Formats in the MongoDB Server manual.<hostname>: MongoDB 部署的网络解决。<port>: MongoDB 部署的端口号。如果省略此参数,驱动程序将使用默认端口号 (27017)。连接MongoDB Atlas 集群时无需端口号。<path to X.509 certificate>:X.509 证书文件的路径。<X.509 certificate password>:X.509 证书的密码。
要使用本页上的代码示例,请将这些占位符替换为您自己的值。
重要
百分比编码
You must percent-encode a username and password before you include them in a MongoDB URI. The quote_plus() method, available in the urllib.parse module, is one way to perform this task. For example, calling quote_plus("and / or") returns the string and+%2F+or.
将用户名或密码作为参数传递给MongoClient时,不要对用户名或密码进行百分号编码。
在应用程序中使用 X.509 身份验证
您可以通过两种方式设置这些选项:将参数传递给 MongoClient 构造函数,或通过连接string中的参数。
client = pymongo.MongoClient("mongodb[+srv]://<hostname>:<port>", tls=True, tlsCertificateKeyFile="<path to X.509 certificate>", tlsCertificateKeyFilePassword="<X.509 certificate password>", authMechanism="MONGODB-X509")
uri = ("mongodb[+srv]://<hostname>:<port>/?" "tls=true" "&tlsCertificateKeyFile=<path to X.509 certificate>" "&tlsCertificateKeyFilePassword=<X.509 certificate password>" "&authMechanism=MONGODB-X509") client = pymongo.MongoClient(uri)
client = pymongo.AsyncMongoClient("mongodb[+srv]://<hostname>:<port>", tls=True, tlsCertificateKeyFile="<path to X.509 certificate>", tlsCertificateKeyFilePassword="<X.509 certificate password>", authMechanism="MONGODB-X509")
uri = ("mongodb[+srv]://<hostname>:<port>/?" "tls=true" "&tlsCertificateKeyFile=<path to X.509 certificate>" "&tlsCertificateKeyFilePassword=<X.509 certificate password>" "&authMechanism=MONGODB-X509") client = pymongo.AsyncMongoClient(uri)
API 文档
要了解有关在 PyMongo 中对应用程序进行身份验证的更多信息,请参阅以下 API 文档: