Docs 菜单
Docs 主页
/ / /
Scala 驱动程序
/

身份验证机制

Scala驾驶员支持所有MongoDB身份验证机制,包括仅在MongoDB Enterprise版中提供的机制。

身份验证档案表示为 MongoCredential类的实例。 MongoCredential类包含每种受支持的身份验证机制的静态工厂方法。

MongoDB 6.0 及更高版本的默认身份验证机制是 SCRAM-SHA-256

要创建使用默认身份验证机制进行身份验证的档案(无论服务器版本如何),请使用createCredential()静态工厂方法创建档案:

val user = "<db_username>" // the username
val source = "<source>" // the source where the user is defined
val password = ... // the password as a character array
val credential = MongoCredential.createCredential(user, source, password)
val mongoClient = MongoClient(MongoClientSettings
.builder()
.applyToClusterSettings(builder =>
builder.hosts(Collections.singletonList(ServerAddress("localhost", 27017))))
.credential(credential)
.build())

或者,您可以使用连接string ,而无需显式指定身份验证机制:

val mongoClient = MongoClient("mongodb://user1:pwd1@host1/?authSource=db1")

自 3.0 以来,Salted 挑战-响应身份验证机制 (SCRAM) 一直是MongoDB的默认身份验证机制。 SCRAM基于 IETF RFC5802 标准,该标准定义了实施使用密码对用户进行身份验证的质询-响应机制的最佳实践。

使用此机制需要将 featureCompatibilityVersion设立为 4.0 或更高版本。

要显式创建类型为SCRAM-SHA-256的档案,请使用createScramSha256Credential()方法:

val user = "<db_username>" // the username
val source = "<source>" // the source where the user is defined
val password = ... // the password as a character array
val credential = MongoCredential.createScramSha256Credential(user, source, password)
val mongoClient = MongoClient(MongoClientSettings
.builder()
.applyToClusterSettings(builder =>
builder.hosts(Collections.singletonList(ServerAddress("localhost", 27017))))
.credential(credential)
.build())

或者,您可以使用显式指定 authMechanism=SCRAM-SHA-256 的连接string :

val mongoClient = MongoClient("mongodb://user1:pwd1@host1/?authSource=db1&authMechanism=SCRAM-SHA-256")

通过 x.509 机制, MongoDB使用 SSL 协商期间提供的 x.509 证书来对名称源自 x.509 证书标识名的用户进行身份验证。

x.509身份验证要求使用带有证书验证的 SSL 连接。 要创建此类档案,请使用 createMongoX509Credential() 静态工厂方法:

val credential = MongoCredential.createMongoX509Credential()
val mongoClient = MongoClient(MongoClientSettings
.builder()
.applyToClusterSettings(builder =>
builder.hosts(Collections.singletonList(ServerAddress("localhost", 27017))))
.credential(credential)
.build())

或者,您可以使用显式指定 authMechanism=MONGODB-X509 的连接string :

val mongoClient = MongoClient("mongodb://subjectName@host1/?authMechanism=MONGODB-X509&ssl=true")

请参阅服务器手册中的“使用 x.509 证书对客户端进行身份验证”教程,学习;了解有关在应用程序中使用 x.509 证书的更多信息。

后退

安全性

在此页面上