Elasticsearch 2.4.6 集成安全认证 SearchGuard 后 java 配置 springboot

简介:
1.elasticsearch版本:2.4.6
2.searchguard版本: 2.4.6
3.java项目:springboot 1.5.10

正文:
一. elasticsearch 集成 searchguard 参考:
二. java配置步骤
1.将ssl证书导入java项目下:
Elasticsearch 2.4.6 集成安全认证 SearchGuard 后 java 配置 springboot_第1张图片
2. pom 添加maven依赖

		
			com.floragunn
			search-guard-ssl
			2.4.6.21
		

3.application.yml 添加配置项

spring
  data:
    elasticsearch:
      cluster-name: elasticsearch
      cluster-nodes: 127.0.0.1:9300
      local: false
      repositories:
        enable: true
      properties:
        authentication: true   #是否开启认证  true-开启 false-关闭
        password: gp+rqt=E
        keystore-path: es_certificate/test/admin-keystore.jks
        truststore-path: es_certificate/test/truststore.jks

4.配置Bean

@Configuration
public class ElasticSearchConfig {

    public Logger logger = LoggerFactory.getLogger(this.getClass());

    static final String COLON = ":";
    static final String COMMA = ",";

    @Autowired
    private ElasticsearchProperties properties; //spring自带读取配置文件的前缀为spring.data.elasticsearch 的 Bean

    @Bean
    public ElasticsearchTemplate elasticsearchTemplate() throws Exception {
        Client client = this.cresteClient();
        return new ElasticsearchTemplate(client);//重写模板中的client
    }

    @Bean
    public Client cresteClient() throws Exception {
        logger.info("初始化 elasticsearch client");
        Map propertiesMap = this.properties.getProperties();
        // 根据认证开关authentication 判断是否添加安全认证来创建Client
        return StringUtils.equals(propertiesMap.get("authentication"), "true") ? this.createAuthenticationTransportClient() : this.createTransportClient();
    }
    
	//spring默认工厂创建Client elasticsearch不加密
    private Client createTransportClient() throws Exception {
        TransportClientFactoryBean factory = new TransportClientFactoryBean();
        factory.setClusterNodes(this.properties.getClusterNodes());
        factory.setProperties(createProperties());
        factory.afterPropertiesSet();
        TransportClient client = factory.getObject();
        return client;
    }
    
	//自定义创建Client elasticsearch加密 配置安全认证
    private Client createAuthenticationTransportClient() throws Exception {
        Map propertiesMap = this.properties.getProperties();
        // 写入jks文件目的是因为项目运行在docker环境下
        String tmp = System.getProperty("java.io.tmpdir");
        logger.info("tmp:{}", tmp);
        String keystore = tmp + File.separator + "keystore.jks";
        String truststore = tmp + File.separator + "truststore.jks";
        InputStream ksInput = null;
        InputStream tsInput = null;
        FileOutputStream keystoreStream = null;
        FileOutputStream truststoreStream = null;
        try {
            ksInput = new ClassPathResource(propertiesMap.get("keystore-path")).getInputStream();
            tsInput = new ClassPathResource(propertiesMap.get("truststore-path")).getInputStream();
            keystoreStream = new FileOutputStream(keystore);
            truststoreStream = new FileOutputStream(truststore);
            IOUtils.copy(ksInput, keystoreStream);
            IOUtils.copy(tsInput, truststoreStream);

        } catch (IOException e) {
            logger.error("写入jks文件异常:{}", e);
        } finally {
            if (keystoreStream != null) {
                keystoreStream.close();
            }
            if (truststoreStream != null) {
                truststoreStream.close();
            }
            if (ksInput != null) {
                ksInput.close();
            }
            if (tsInput != null) {
                tsInput.close();
            }
        }
        Settings settings = Settings.builder()
                .put("path.home", ".")
                .put("cluster.name", this.properties.getClusterName())
                .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENABLED, true)
                .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_FILEPATH, keystore)
                .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_FILEPATH, truststore)
                .put(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_PASSWORD, propertiesMap.get("password"))
                .put(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_PASSWORD, propertiesMap.get("password"))
                .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_PASSWORD, propertiesMap.get("password"))
                .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_PASSWORD, propertiesMap.get("password"))
                .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENFORCE_HOSTNAME_VERIFICATION, false)
                .build();
        TransportClient client = TransportClient
                .builder()
                .settings(settings)
                .addPlugin(SearchGuardSSLPlugin.class)
                .build();

        for (String clusterNode : split(properties.getClusterNodes(), COMMA)) {
            String hostName = substringBeforeLast(clusterNode, COLON);
            String port = substringAfterLast(clusterNode, COLON);
            Assert.hasText(hostName, "[Assertion failed] missing host name in 'clusterNodes'");
            Assert.hasText(port, "[Assertion failed] missing port in 'clusterNodes'");
            logger.info("adding transport node : " + clusterNode);
            client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(hostName), Integer.valueOf(port)));
        }
        return client;
    }

    private Properties createProperties() {
        Properties properties = new Properties();
        properties.put("cluster.name", this.properties.getClusterName());
        properties.putAll(this.properties.getProperties());
        return properties;
    }
}

你可能感兴趣的:(Elasticsearch)