24

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?

2 Answers 2

54

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:

Sign up to request clarification or add additional context in comments.

1 Comment

can you tell me how to do the same thing if I am using search-guard instead of X-Pack?
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;
                        }
                ));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.