我是 Elastic 搜索的新手。通过Java High Level Rest Client
将我的 Spring 启动应用程序与 Elastic 搜索集成。
我已经按如下方式配置了 JHLRC 豆,它工作正常:
@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 未授权。
有人可以帮我做哪些进一步的改变,同时配置Java High Level Rest Client
以点击安全的 Elastic 搜索吗?
它在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;
}
您需要包含访问 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());