Elastic Search + Search Guard做es安全认证(RestHighLevelClient)。

首先:es集群安装Search Guard,运维完成,或者参考Search Guard官网进行安装。(我也不会)

需要4个东西:truststore.jks文件,truststore.jks的秘钥,es的登录用户、密码

在没有search guard的时候,实例化es的就不多说了。(网上自己搜)

建议使用es的java高级客户端:RestHighLevelClient,在es7之后已经不支持使用transportclient。

下面是源码:

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.ssl.SSLContexts;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.SSLContext;
import java.io.File;

@Configuration
@Slf4j
public class ElasticSearchConfiguration extends AbstractFactoryBean {


    @Value("${elasticsearch.host}")
    private String host;//es-node1.com,es-node2.com

    @Value("${elasticsearch.port}")
    private String port;//9200,9200

    @Value("${elasticsearch.cluster-name}")
    private String clusterName;

    @Value("${elasticsearch.truststore.password}")
    private String truststorePasswordStr;//truststore.jks的生成秘钥

    @Value("${elasticsearch.truststore.path}")
    private String truststorePath;//truststore.jks的路径

    @Value("${elasticsearch.username}")
    private String username;

    @Value("${elasticsearch.password}")
    private String password;

    @Value("${elasticsearch.scheme}")
    private String scheme;//加上searchguard之后是https

    private static int connectTimeOut = 1000; // 连接超时时间
    private static int socketTimeOut = 30000; // 连接超时时间
    private static int connectionRequestTimeOut = 500; // 获取连接的超时时间

    private RestHighLevelClient restHighLevelClient;

    @Override
    public void destroy() throws Exception {
        // 关闭Client
        if (restHighLevelClient != null) {
            restHighLevelClient.close();
        }
    }

    @Override
    public Class getObjectType() {
        return RestHighLevelClient.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }

    @Override
    protected RestHighLevelClient createInstance() throws Exception {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        //用户名密码
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

        //(searchguard需要加上,构建sslcontext)
        //truststore的密码
        boolean trustSelfSigned = true;
        char[] truststorePassword = truststorePasswordStr.toCharArray();
        SSLContext sslContextFromJks = SSLContexts
                .custom()
                .loadTrustMaterial(new File(truststorePath), truststorePassword, trustSelfSigned ? new TrustSelfSignedStrategy() : null)
                .build();


        //多个节点
        String[] hostArray = host.split(",");
        String[] portArray = port.split(",");
        if (hostArray.length != portArray.length) {
            log.error("Elastic Search 初始化失败:Host和Port不对应,host:{} ,port:{}", hostArray, portArray);
            return null;
        }
        HttpHost[] httpHosts = new HttpHost[hostArray.length];
        for (int i = 0; i < hostArray.length; i++) {
            httpHosts[i] = new HttpHost(hostArray[i], Integer.parseInt(portArray[i]), scheme);
        }
        try {
            RestClientBuilder builder = RestClient.builder(httpHosts);
            // 异步httpclient连接延时配置
            builder.setRequestConfigCallback(requestConfigBuilder -> {
                requestConfigBuilder.setConnectTimeout(connectTimeOut);
                requestConfigBuilder.setSocketTimeout(socketTimeOut);
                requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut);
                return requestConfigBuilder;
            });

            //设置安全(searchguard)
            builder.setHttpClientConfigCallback(httpClientBuilder ->
                    httpClientBuilder
                            .setDefaultCredentialsProvider(credentialsProvider)
                            .setSSLContext(sslContextFromJks)
            );

            restHighLevelClient = new RestHighLevelClient(builder);
        } catch (Exception e) {
            log.error("Elastic Search 初始化失败:" + e.getMessage());
        }
        return restHighLevelClient;
    }
}

 

你可能感兴趣的:(elastic,search)