'Add authentication in elasticsearch high level client for Java

I am using an elasticsearch instance in elastic cloud instance secured with X-PACK.

I had been using the high level rest client before without any problems but I am unable to find how to send the basic authentication header on it.

I have tried to put the credentials as part of the URL but it didn't seem to be able to connect in that case.

Has anyone succeed to connect to a secured elasticsearch with high level rest client?



Solution 1:[1]

Follow simple steps for making the RestHighLevelClient ready for connecting TLS+Auth Elastic Search

Create a CredentialsProvider using BasicCredentialsProvider provided by Apache httpclient like below

final CredentialsProvider credentialProvider = new BasicCredentialsProvider();
    credentialProvider.setCredentials(
            AuthScope.ANY,
            new UsernamePasswordCredentials(
                    ES_USERNAME,
                    ES_PASSWORD
            ));

Create a HttpHost provide by apache using Host, Port and Protocol like below

HttpHost httpHost = new HttpHost("ELASTIC_SEARCH_HOST", 9200, "https");

Here I used "https" since TLS is enabled on ES. You can use "http" for normal ES.

And the final step is to create RestHighLevelCLient like below

RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(nodes)
                .setHttpClientConfigCallback(httpAsyncClientBuilder -> {
                            httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialProvider);
                            return httpAsyncClientBuilder;
                        }
                ));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shubham Kumar