spring-data-elasticsearch中集成search Guard

近期项目中接入elasticsearch,供管理台大表的数据模糊查询,在原有spring项目中引入spring-data-elasticsearch,以及使用searchGuard进行鉴权

版本

spring-data-es与使用的es版本有直接关系,这里找到响应的spring-data-es版本。注意spring-data-es依赖包中包含spring的相关框架,如果与原有系统的冲突需要兼容
spring-data-elasticsearch中集成search Guard_第1张图片
search Guard的版本也要与es相匹配
spring-data-elasticsearch中集成search Guard_第2张图片

Client

es的java api主要提供了两种client,一个是使用http协议的rest client,一个是基于tcp的transport client,也即是es针对java语言封装的api,在高版本中默认会使用http协议

static class Config {

  @Bean
  Client client() {
  	Settings settings = Settings.builder()
  	  .put("cluster.name", "elasticsearch")   
      .build();
  	TransportClient client = new PreBuiltTransportClient(settings);
  	//注意tcp的端口与http不同
    client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1")
      , 9300));                               
    return client;
  }
}
 @Bean
  RestHighLevelClient client() {

    ClientConfiguration clientConfiguration = ClientConfiguration.builder() 
      .connectedTo("localhost:9200", "localhost:9201")
      .build();

    return RestClients.create(clientConfiguration).rest();                  
  }
}

在spring-data-es中,这两种client也会分别对应ElasticsearchTemplate和ElasticsearchRestTemplate

searchGuard

使用searchGuard需要额外引入依赖包,必须与es集群版本匹配

<dependency>
    <groupId>com.floragunngroupId>
    <artifactId>search-guard-6artifactId>
    <version>${sg.version}version>
    <scope>providedscope>
dependency>

在原有的transport setting追加ssl相关的证书和密码

Settings.Builder settingsBuilder = 
  Settings.builder()
  .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_PEMCERT_FILEPATH,"")
  .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_PEMKEY_FILEPATH,"")
  .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_PEMKEY_PASSWORD,"")
  .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_PEMTRUSTEDCAS_FILEPATH, "")
  ...
  Settings settings = settingsBuilder.build();

并在client中引入search Guard插件

TransportClient tc = 
  new PreBuiltTransportClient(settings, SearchGuardPlugin.class)
  .addTransportAddress(...)

鉴权有两种,这里采用的是用户密码的方式,在client请求线程中加入。从实践情况下看,如已存在Authorization的header可以会报header已存在异常,建议在put之前先检查下。

TransportClient client = ...

client.threadPool().getThreadContext().putHeader("Authorization", "Basic "+encodeBase64("username:password"));

查看文献:
https://www.elastic.co/guide/en/elasticsearch/client/java-api/6.8/transport-client.html
https://docs.spring.io/spring-data/elasticsearch/docs/3.2.3.RELEASE/reference/html/#elasticsearch.clients.transport
https://docs.search-guard.com/6.x-25/elasticsearch-transport-clients-search-guard

你可能感兴趣的:(工作总结)