如何使用版本4.4中的MongoDB Java驱动程序使用SSL和密码身份验证连接到副本集



如何使用版本4.4中的MongoDB Java驱动程序使用SSL和密码身份验证连接到副本集?

你能举几个例子吗?

为了使用SSL,您需要在密钥库中拥有CA证书和私钥(或者如果您喜欢使用两个不同的密钥库(。虽然您需要设置一些Java系统属性来声明您的密钥库以及如何访问它们,但所有其他参数都是通过MongoClientSettings.Builder类设置的。

下面有一个小示例,您可以使用SSL和基于密码的身份验证来连接到MongoDB副本集:

public static MongoClient createMongoClient(MongoDBConnectionParameters parameters) {
MongoClientSettings.Builder builder = MongoClientSettings.builder();
if(parameters.getPassword() != null) {
// User name and password
MongoCredential mongoCredential = com.mongodb.MongoCredential.createCredential(parameters.getUser(),
parameters.getAuthDB(), parameters.getPassword().toCharArray());
builder.credential(mongoCredential);
}
if(parameters.getServerAddressList() != null) {
// using replica set
ArrayList<ServerAddress> serverAddresses = parameters.getServerAddressList().entrySet().stream()
.map(e -> new ServerAddress(e.getKey(), e.getValue())).collect(Collectors.toCollection(ArrayList::new));
builder.applyToClusterSettings(b -> b.hosts(serverAddresses));
} else {
String connectionString = String.format("mongodb://%s:%d/", parameters.getMongoServer(), parameters.getMongoPort());
builder.applyConnectionString(new ConnectionString(connectionString));
}
if(parameters.isTls()) {
// using SSL
builder.applyToSslSettings(b -> b.enabled(true));
setupSsl(parameters);
}
return MongoClients.create(builder.build());
}
private static void setupSsl(MongoDBConnectionParameters parameters) {
System.setProperty("javax.net.ssl.trustStore", parameters.getTrustStore().toString());
System.setProperty("javax.net.ssl.trustStoreType", "JKS");
final String trustStorePassword = "thepassword";
System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
System.setProperty("javax.net.ssl.keyStore", parameters.getKeystoreFile().toString());
System.setProperty("javax.net.ssl.keyStoreType", "JKS");
String keystorePassword = "thepassword";
System.setProperty("javax.net.ssl.keyStorePassword", keystorePassword);
}

这是Maven与MongoDB驱动程序的依赖关系:

<!-- https://mvnrepository.com/artifact/org.mongodb/mongodb-driver-sync -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.4.0</version>
</dependency>

相关内容

  • 没有找到相关文章