javaspring-bootsecurityelasticsearchelasticsearch-high-level-restclient

How to hit Secure Elastic Search through Java High Level Rest Client


I'm new to Elastic search. Integrated my Spring boot application with Elastic search through Java High Level Rest Client.

I've configured JHLRC bean as below and it worked fine:

@Bean(destroyMethod = "close")
public RestHighLevelClient client() {
  RestHighLevelClient client = new RestHighLevelClient(
      RestClient.builder(new HttpHost("localhost", 9200, "http")));
  return client;
}

Started exploring the security for Elasticsearch, after setup certificate and passwords, I've enabled security by providing below properties :

xpack.security.enabled: true
xpack.security.transport.ssl.enabled: true
xpack.security.transport.ssl.verification_mode: certificate
xpack.security.transport.ssl.keystore.path: elastic-certificates.p12
xpack.security.transport.ssl.truststore.path: elastic-certificates.p12

I'm able to login in kibana by using a created username and password but getting 401 Unauthorized while hitting any Elastic search API through JHLRC.

Can someone please help me on what further changes I've to make while configuring Java High Level Rest Client to hit secure Elastic search?


Solution

  • You need to include the Basic credentials which you are giving while accessing the kibana, below code shows you can pass the username and password in JHLRC.

    First, create the encoded string from your username and password, you can use the superuser elastic which has all the access by using the below code.

    private String getEncodedString(String username, String password) {
            return HEADER_PREFIX + Base64.getEncoder().encodeToString(
                    (username + ":" + password)
                            .getBytes());
        }
    

    Now in your request option, you pass the auth header which will include the base 64 encoded string which you will get from the above method.

    RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder()
                    .addHeader(AUTH_HEADER_NAME, getEncodedString(basicCredentials));
    

    Last, you just need to build the object of above requestion options builder and pass it to your client in any request like below:

    GetResponse getResponse = restHighLevelClient.get(getRequest, builder.build());