将sslInvalidHostNameAllowed = true添加到SpringBoot和Mongodb

时间:2019-01-28 09:13:09

标签: java spring mongodb spring-boot ssl

我正在使用Sping引导2.1.2和mongodb编写REST API。 我在Bluemix上有一个MongoDB的撰写实例。 该实例将SSL与 -sslAllowInvalidCertificates

选项一起使用

我可以使用NAVICAT之类的软件连接到它,只需复制并粘贴字符串连接就可以了,在这里,我的应用程序属性带有URI字符串:

spring.data.mongodb.uri=mongodb://admin:password@site1.composedb.com:19580,site2.composedb.com:19580/dbname?authSource=admin&ssl=true

当我尝试启动该应用程序时,springboot应用程序无法正常工作,因为我认为它需要证书,而我却没有证书,我也不想证书:

Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

我不知道如何在我的springboot应用程序中以及在何处设置客户端选项 sslInvalidHostNameAllowed(true)

谢谢

更新-已解决

我设法解决了它,扩展了 AbstractMongoConfiguration 并覆盖了 mongoClient()这样的方法:

@Override
public MongoClient mongoClient() {
    try {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        }).build();

        MongoClientOptions.Builder builder = new MongoClientOptions.Builder().sslEnabled(true).sslInvalidHostNameAllowed(true).sslContext(sslContext);
        MongoClientURI connectionString = new MongoClientURI("mongodb:Strign connection", builder);
        return new MongoClient(connectionString);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

0 个答案:

没有答案