Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add authentication in elasticsearch high level client for JAVA

Tags:

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?

like image 770
pedromarce Avatar asked Jan 10 '18 10:01

pedromarce


1 Answers

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:

  • https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-getting-started-initialization.html
  • https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/_basic_authentication.html
like image 123
Bless Avatar answered Sep 24 '22 08:09

Bless