工程

Elasticsearch 添加 Shield 后 TransportClient 如何连接?

Shield 是 Elasticsearch 一个安全防护插件,提供了权限访问控制和日志审计功能,企业可以很方便的和 LDAP 或是 ActiveDirectory 进行集成,重用现有的安全认证体系。
Elasticsearch 使用了 Shield 后,Elasticsearch 就需要权限才能访问了。和默认的调用方式有些不同,下面简单介绍一下 HTTP 和 TCP 两种方式的连接。
关于 Shield 的安装和配置我这里不就具体介绍,现在先创建了一个用户名和密码都是 tribe_user 的用户,权限是 admin。

1. HTTP方式
现在直接访问 ES 的 HTTP 接口就会报错。

curl http://localhost:9200
{"error":{"root_cause":[{"type":"security_exception","reason":"missing authentication token 
for REST request [/]","header":{"WWW-Authenticate":"Basic 
realm=\"shield\""}}],"type":"security_exception","reason":"missing authentication token for 
REST request [/]","header":{"WWW-Authenticate":"Basic realm=\"shield\""}},"status":401}

Shield 支持 HttpBasic 验证,所以正确的访问姿势是:

curl -u tribe_user:tribe_user http://localhost:9200
{
    "name" : "Melter",
    "cluster_name" : "elasticsearch",
    "version" : {
        "number" : "2.1.1",
        "build_hash" : "805c528f3167980046f224310f9147fa745e5371",
        "build_timestamp" : "2015-12-09T20:23:16Z",
        "build_snapshot" : false,
        "lucene_version" : "5.3.1"
    },
    "tagline" : "You Know, for Search"
}

如果是浏览器访问的话,第一次访问会弹出验证窗口。后续只要不关闭这个浏览器保持这个 session 就能一直访问。
注意 HttpBasic 是不安全的认证方式,仅供开发调试使用。生产环境还需要结合 HTTPS 的加密通道使用。

2. TransportClient 方式的访问 Shield 加防的 Elasticsearch,步骤如下:
2.1 如果你是 maven 管理的项目,可以在 pom.xml 文件里添加 Elasticsearch 的 maven 仓库源。

<repositories>
   <repository>
      <id>elasticsearch-releases</id>
      <url>https://maven.elasticsearch.org/releases</url>
      <releases>
         <enabled>true</enabled>
      </releases>
      <snapshots>
         <enabled>false</enabled>
      </snapshots>
    </repository>
</repositories>

2.2 添加依赖的配置。

<dependency>
   <groupId>org.elasticsearch.plugin</groupId>
   <artifactId>shield</artifactId>
   <version>2.1.1</version>
</dependency

2.3 构建 TransportClient 的地方增加访问用户的配置。

import org.elasticsearch.shield.ShieldPlugin;
import org.elasticsearch.shield.authc.support.SecuredString;
import static
org.elasticsearch.shield.authc.support.UsernamePasswordToken.basicAuthHeaderValue;
String clusterName="elasticsearch";
String ip= "127.0.0.1";
Settings settings = Settings.settingsBuilder()
        .put("cluster.name", clusterName)
         .put("shield.user", "tribe_user:tribe_user")
        .build();
try {
    client = TransportClient.builder()
            .addPlugin(ShieldPlugin.class)
            .settings(settings).build()