Overview:
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:
- From the elastic part, I installed xpack based on Install xpack and everything is fine outside of Api. Then added username api with password apipass as a new elastic super user.
- From API side, I updated the code as follows for secure connection: Java Client and Security
My code changes in elastic configurations:
@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;
}
}
Issue:
When trying to run the elastic query via application, the following exception will be raised:
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]
I would appreciate if anyone could share their genuine solution with me to connect Spring boot application to elasticsearch with basic authentication?