Search code examples
securityauthenticationelasticsearchresthighlevelclient

Configure Elasticsearch rest high level client with Basic credential provider


This question was asked in the follow-up question to my this SO answer of how to secure JHLRC in this comment, where I explained how to send Basic Credential in Elasticsearch JHLRC request but it was not at the client level and was at the request level.

I feel configure at the client level, would avoid repeating the same code again in cases, where you are dealing with only a few users it would be helpful to configure the credentials in the client itself.


Solution

  • You can follow the below steps as mentioned in this official link.

    Create CredentialsProvider using the BasicCredentialsProvider.

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

    Now use the CredentialsProvider while building the rest client(JHLRC).

    RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost(scannerConfiguration.getElasticsearchConfig().getHost(),
                            scannerConfiguration.getElasticsearchConfig().getPort(),
                            "http")).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                        @Override
                        public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                            return httpClientBuilder
                                    .setDefaultCredentialsProvider(credentialsProvider);
                        }
                    }));