如何通过 Java 高级 Rest 客户端访问 Secure Elastic Search

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

我是 Elastic 搜索的新手。通过 Java High Level Rest Client.

将我的 Spring 引导应用程序与弹性搜索集成

我已经如下配置了 JHLRC bean,它工作正常:

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

开始探索 Elasticsearch 的安全性,在设置证书和密码后,我通过提供以下属性启用了安全性:

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

我可以使用创建的用户名和密码登录 kibana,但在通过 JHLRC 进行任何 Elastic 搜索 API 时收到 401 Unauthorized。

有人可以帮助我在配置 Java High Level Rest Client 以点击安全 Elastic 搜索时需要做哪些进一步的更改吗?

您需要包含访问 kibana 时提供的基本凭据,下面的代码显示您可以在 JHLRC 中传递用户名和密码。

首先,根据您的用户名和密码创建编码字符串,您可以使用超级用户 elastic,使用以下代码即可获得所有访问权限。

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

现在在您的请求选项中,您传递身份验证 header,其中将包含您将从上述方法获得的 base 64 编码字符串。

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

最后,您只需要构建上述请求选项构建器的 object,并在任何请求中将其传递给您的客户,如下所示:

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

在 JHLRC 中进行以下更改后它起作用了:

@Bean(destroyMethod = "close")
  public RestHighLevelClient client() {

    final BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
    basicCredentialsProvider
        .setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "password_generated_by_elastic_search"));

    RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
        RestClient.builder(new HttpHost("localhost", 9200, "http"))
            .setHttpClientConfigCallback(new HttpClientConfigCallback() {
              @Override
              public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                httpClientBuilder.disableAuthCaching();
                return httpClientBuilder.setDefaultCredentialsProvider(basicCredentialsProvider);
              }
            })

    );

    return restHighLevelClient;
  }