1

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

我已经如下配置了 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命中安全弹性搜索时需要做哪些进一步的更改吗?

4

2 回答 2

2

在 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;
  }
于 2020-06-24T03:56:04.500 回答
1

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

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

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

现在在您的请求选项中,您传递 auth 标头,该标头将包含您将从上述方法获得的 base 64 编码字符串。

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

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

GetResponse getResponse = restHighLevelClient.get(getRequest, builder.build());
于 2020-06-23T12:22:43.210 回答