请选择 进入手机版 | 继续访问电脑版
MSIPO技术圈 首页 IT技术 查看内容

ES配置https认证和用户密码授权的方法

2023-07-13

   最近由于安全需要,需要对使用es组件的部分升级https认证和用户密码通讯,调整原有方法如下:

 RestClientBuilder clientBuilder = RestClient.builder(new HttpHost(host, port, elasticsearchProtocol));
        // 1. 设置公共请求头,每个请求都会带上这个请求头
        setDefaultHeaders(clientBuilder);
        // 3. 设置节点失败监听器
        setFailListener(clientBuilder);
        // 4. 设置节点选择器
        clientBuilder.setNodeSelector(NodeSelector.SKIP_DEDICATED_MASTERS);
        // 5. 配置HTTP异步请求ES的线程数
        setHttpClientConfigCallback(clientBuilder);
        // 6. 配置连接超时和套接字超时
        setRequestConfigCallback(clientBuilder);
        if ("true".equals(esSecurityEnable)) {
            //启用es加密
            // 8. 配置通信加密 +  安全认证
            setSSLContext(clientBuilder);
        }
        return new RestHighLevelClient(clientBuilder);
    private void setSSLContext(RestClientBuilder clientBuilder){

        try{
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[] { new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {}
                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) {}
                @Override
                public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
            }}, null);

            // 认证相关配置
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(esUserName, esPass));

            clientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                @Override
                public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                    return httpClientBuilder.
                            setDefaultCredentialsProvider(credentialsProvider).
                            setSSLContext(sslContext).
                            setSSLHostnameVerifier(new HostnameVerifier() {
                                @Override
                                public boolean verify(String hostname, SSLSession session) {
                                    // TODO Auto-generated method stub
                                    return true;
                                }
                            });
                }
            });
        }catch (Exception e){
            System.out.println("设置SSL正式错误!");
            e.printStackTrace();
        }
    }

相关阅读

热门文章

    手机版|MSIPO技术圈 皖ICP备19022944号-2

    Copyright © 2024, msipo.com

    返回顶部