gpt4 book ai didi

mongodb - Spring Boot mongo tls 证书

转载 作者:行者123 更新时间:2023-12-04 22:37:53 55 4
gpt4 key购买 nike

我已经在 mongod.conf 中设置了 TLS。我需要使用 spring boot 连接到我现在需要 tls 的 mongo。在 MongoCompass 中,我将证书颁发机构、客户端证书和客户端私钥相应地设置为 root-ca.pem、test.pem 和 test.pem,并且我能够连接。如何在 mongoclientoptions 中正确指定 root-ca.pem 和 test.pem 以连接到我的 mongo?
这是我的 mongod.conf

# network interfaces
net:
port: 27017
bindIp: 127.0.0.1
tls:
mode: requireTLS
certificateKeyFile: C:\TLSServerMongo\test.pem
CAFile: C:\TLSServerMongo\root-ca.pem
clusterFile: C:\TLSServerMongo\test.pem
allowInvalidCertificates: true
FIPSMode : false
这是我的 mongoclientoptions
   @Bean
public MongoClientOptions mongoClientOptions() {
MongoClientOptions.Builder mongoClientOptions = MongoClientOptions.builder().sslInvalidHostNameAllowed(true).sslEnabled(true);
try {
// String fileName = directory + RDS_COMBINED_CA_BUNDLE;
String fileName = "C:\\TLSServerMongo\\test.pem";
InputStream is = new FileInputStream(fileName);
// You could get a resource as a stream instead.

CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate caCert = (X509Certificate) cf.generateCertificate(is);

TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null); // You don't need the KeyStore instance to come from a file.
ks.setCertificateEntry("caCert", caCert);

tmf.init(ks);

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
mongoClientOptions.sslContext(sslContext);
} catch (Exception e) {
LOGGER.error(e.getMessage());
}


return mongoClientOptions.build();
}
这是我的 MongoClient
  public @Bean
MongoClient mongoClient() {
List<MongoCredential> allCred = new ArrayList<>();
allCred.add(MongoCredential.createCredential(username, database, password.toCharArray()));
MongoClient client = new MongoClient((new ServerAddress(this.myHost, this.myPort)), allCred, mongoClientOptions());
client.setWriteConcern(WriteConcern.ACKNOWLEDGED);

return client;
}

最佳答案

创建一个 .jks 文件作为证书并在 Spring Boot mongo 客户端中使用它是一个好主意...
请引用此以将您的 .pem 证书转换为 JKS Convert .pem files to .jks
一旦您的系统上的 keystore 中有 .jks,我们就可以使用它,或者您可以按照此示例使用 jks 进行连接...
Connecting to MongoDB from spring boot app using ssl
或者
https://dba.stackexchange.com/questions/206462/how-to-configure-ssl-mongodb-connection-in-yml-file-spring-boot
希望能帮助到你!

关于mongodb - Spring Boot mongo tls 证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62569729/

55 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com