23

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?

Sled
  • 18,541
  • 27
  • 119
  • 168
pedromarce
  • 5,651
  • 2
  • 27
  • 27

2 Answers2

51

You can specify the username and password to the Java Low Level REST Client and pass the Low Level REST Client to the RestHighLevelClient instance.

final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
        new UsernamePasswordCredentials("user", "password"));

RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200))
        .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
            @Override
            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
        });

RestHighLevelClient client = new RestHighLevelClient(builder);

References:

Bless
  • 5,052
  • 2
  • 40
  • 44
0

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;
                        }
                ));
Shubham Kumar
  • 121
  • 1
  • 4