将Elasticsearch Java REST API与自签名证书一起使用

时间:2017-11-16 16:19:45

标签: java rest elasticsearch ssl-certificate

我想使用Java REST API(RestHighLevelClient)通过HTTPS与Elasticsearch 5.6服务器通信。但是,服务器的证书是自签名的,当我尝试连接时会抛出SSLHandshakeException。

有没有办法配置REST客户端以接受自签名证书?

1 个答案:

答案 0 :(得分:1)

我使用自定义Java密钥库进行此操作。这是我的代码:

CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

final SSLContext sslContext = SSLContexts.custom()
        .loadTrustMaterial(new File("my_keystore.jks"), keystorePassword.toCharArray(),
            new TrustSelfSignedStrategy())
        .build();


RestClient client = RestClient.builder(new HttpHost(host, port, scheme)).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
        .setDefaultCredentialsProvider(credentialsProvider)
        .setSSLContext(sslContext)
).build();

要创建密钥库,我通过Firefox下载了域的证书,并使用了:

keytool -import -v -trustcacerts -file my_domain.crt -keystore my_keystore.jks -keypass password -storepass password