Elasticsearch HTTP authentication in Spring

不羁的心 提交于 2019-12-04 10:14:30
G Quintana

Spring Data Elasticsearch is base on the official Elasticsearch Java Client which uses the binary Transport procol (not the REST HTTP procol like PHP).

If you're using Shield to secure your Elasticsearch, then you can set the user/password on the Transport client/Transport procol

TransportClient client = TransportClient.builder()
    .addPlugin(ShieldPlugin.class)
    .settings(Settings.builder()
        .put("cluster.name", "yourcluster")
        .put("shield.user", "youruser:yourpassword")
        ...
        .build())

If you wan't to use the HTTP protocol from Java code then there are to community clients:

But these solutions are not compatible with Spring Data

Paul Podgorsek

If you are using ElasticSearch's Docker image, it comes with X-Pack:

The above links refer to the 5.5 version as this is the version supported by Spring Data ElasticSearch at the time of my answer. To summarize those links, here are the steps you have to follow:

  1. Include the org.elasticsearch.client:x-pack-transport dependency in your project. You might need to add this repository in the repositories section in your build.gradle/pom.xml: https://artifacts.elastic.co/maven as follows:

    repositories { maven { url "https://artifacts.elastic.co/maven" } }

  2. Replace your transport client by one using X-Pack:

    import org.elasticsearch.xpack.client.PreBuiltXPackTransportClient;
    ...
    TransportClient client = new PreBuiltXPackTransportClient(Settings.builder()
        .put("cluster.name", "myClusterName")
        .put("xpack.security.user", "transport_client_user:changeme")
        ...
        .build())
    .addTransportAddress(new InetSocketTransportAddress("localhost", 9300))
    .addTransportAddress(new InetSocketTransportAddress("localhost", 9301));
    

Important: in addition to the above steps for HTTP authentication, you should also set up HTTPS connections to make sure the passwords are not sent in clear over the network.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!