Using Elasticsearch Java REST API with self signed

2019-07-17 01:30发布

问题:

I want to use the Java REST API (RestHighLevelClient) to communicate with an Elasticsearch 5.6 server over HTTPS. However, the certificate for the server is self signed and when I try to connect it throws a SSLHandshakeException.

Is there a way of configuring the REST client to accept self signed certificates?

回答1:

I got this working using a custom Java Key Store. Here's my code:

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();

To create the keystore, I downloaded the cert for the domain through Firefox, and used:

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