Search code examples
javaauthenticationelasticsearchcertificateelasticsearch-x-pack

ES 7.4.1 - Authentication [Rest API]


I’m a newbie in ES and I have a task in my new job to upgrade from 6.4.2 to 7.4.1 – From TCP client to Rest High Level API.

Previously we built the client like this:

Settings settings = Settings.builder()
      .put("xpack.security.user", String.format("%s:%s",esJavaUser,esJavaPassword))
      .put("cluster.name", esClusterName)
      .put("xpack.security.transport.ssl.enabled", xpackSecurityTransportSslEnabled)
      .put("xpack.ssl.certificate_authorities", xpackSslCertificateAuthorities)
      .build();

 client = new PreBuiltXPackTransportClient(settings);

Now, in rest API, it’s changed to this:

final CredentialsProvider credentialsProvider =
        new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
        new UsernamePasswordCredentials(esJavaUser, esJavaPassword));

RestClientBuilder restClientBuilder = RestClient.builder(hosts)
        .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
                .setDefaultCredentialsProvider(credentialsProvider));
restHighLevelClient = new RestHighLevelClient(restClientBuilder);

With this build I set ES user and password by CredentialsProvider but what about ssl.enabled and certificate_authorities”? how should I provided them with rest API?


Solution

  • I got an answer from ES forum (didn't thought to ask there first..)

    Because, as developer, I always looking for answer here, in stackoverflow, I decide to not delete this question and copy TimV answer:

    The documentation you are looking for is here: https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.4/_encrypted_communication.html

    SSL is automatically enabled (or not) based on the scheme (protocol) in the HttpHost objects you pass to the builder.

    RestClient.builder(hosts)

    If you are using SSL, you want to pass "https" as the scheme (3rd argument) when you construct the HttpHost objects (hosts).

    Unfortunately there is no simple means to pass certificate_authorities to the Rest client, you need to turn those certificates into a standard Java truststore. You can probably find some sample code on the web ("convert PEM certificates to Java truststore"), but the gist of it is:

    1. Open the certificate authority files as an InputStream
    2. Create a X.509 certificate factory: java.security.cert.CertificateFactory.getInstance("X.509")
    3. Call generateCertificates on the certificate factory to read those certificate files into java Certificate objects
    4. Construct an empty KeyStore object
    5. Add the loaded certificates as trusted entries
    6. Pass that to SSLContextBuilder.loadTrustMaterial

    Link: https://discuss.elastic.co/t/es-7-4-1-authentication-rest-api/211969