title: Spring boot connect to Elasticsearch with basic authentication
body: <p><strong>Overview:</strong> </p>
  
  <p>I tried non-secure connection between API and my local elasticsearch and everything worked well. To do securing connection, I did the following steps to add xpack plugin on my elastic and used it in the api:  </p>
  
  <ul>
  <li>From the elastic part, I installed xpack based on <a href="https://www.elastic.co/guide/en/elasticsearch/reference/6.0/setup-xpack.html" rel="nofollow noreferrer">Install xpack </a>and everything is fine outside of Api. Then added username <strong>api</strong> with password <strong>apipass</strong> as a new elastic super user.</li>
  <li>From API side, I updated the code as follows for secure connection:
  <a href="https://www.elastic.co/guide/en/x-pack/5.2/java-clients.html" rel="nofollow noreferrer">Java Client and Security</a></li>
  </ul>
  
  <p>My code changes in elastic configurations: </p>
  
  <pre><code>@Bean
  public TransportClient transportClient() throws UnknownHostException {
      Settings settings = Settings.builder()
          .put("cluster.name", clusterName)
          .put("xpack.security.user", "api:apipass")
          .build();
      try (TransportClient client = new PreBuiltXPackTransportClient(settings)
          .addTransportAddress(new TransportAddress(InetAddress.getByName(host), tcpPort))) {            
          String token = basicAuthHeaderValue("api", new SecureString("apipass".toCharArray()));
          client.filterWithHeader(Collections.singletonMap("Authorization", token))
              .prepareSearch().get();
  
          return client;
      }
  }
  </code></pre>
  
  <p><strong>Issue:</strong> </p>
  
  <p>When trying to run the elastic query via application, the following exception will be raised: </p>
  
  <pre><code>Caused by: java.lang.IllegalStateException: transport client is closed
  at org.elasticsearch.client.transport.TransportClientNodesService.execute(TransportClientNodesService.java:243) ~[elasticsearch-6.0.0.jar:6.0.0]
  at org.elasticsearch.client.transport.TransportProxyClient.execute(TransportProxyClient.java:59) ~[elasticsearch-6.0.0.jar:6.0.0]
  at org.elasticsearch.client.transport.TransportClient.doExecute(TransportClient.java:357) ~[elasticsearch-6.0.0.jar:6.0.0]
  at org.elasticsearch.client.support.AbstractClient.execute(AbstractClient.java:405) ~[elasticsearch-6.0.0.jar:6.0.0]
  at org.elasticsearch.client.support.AbstractClient.execute(AbstractClient.java:394) ~[elasticsearch-6.0.0.jar:6.0.0]
  at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:46) ~[elasticsearch-6.0.0.jar:6.0.0]
  at org.elasticsearch.action.ActionRequestBuilder.get(ActionRequestBuilder.java:53) ~[elasticsearch-6.0.0.jar:6.0.0]
  </code></pre>
  
  <p><strong>I would appreciate if anyone could share their genuine solution with me to  connect Spring boot application to elasticsearch with basic authentication?</strong>  </p>