安装x-pack 
bin/elasticsearch-plugin install x-pack

修改elasticsearch.yml配置,新增(如果有,不用新增)
http.cors.enabled: true
http.cors.allow-origin: "*"
http.cors.allow-headers: Authorization
xpack.security.enabled: true

重启elasticsearch
./bin/elasticsearch -d

创建新的superuser:admin用户,设置密码
curl -X POST "http://elastic:changeme@ip:9200/_xpack/security/user/admin?pretty" -d '{
"password":"123456",
"roles":["superuser" ],
"metadata":{"intelligence":7}
}'

失效原superuser:elastic
curl -X PUT "http://admin:123456@ip:9200/_xpack/security/user/elastic/_disable?pretty"

java代码修改
引入x-pack-transport.jar包(版本号与elasticsearch对应):

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>x-pack-transport</artifactId>
    <version>5.6.1</version>
</dependency>
Settings settings = Settings.builder()
        .put("cluster.name", clusterName)
        .put("client.transport.sniff", true)
        // 设置xpack权限用户
        .put("xpack.security.user", userName + ":" + password)
        .build();
        
 Client client = new PreBuiltXPackTransportClient(settings)
        .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(clusterHost), clusterPort));

注:参考中,加了ssl部分的,并未使用及验证,有需要可以借鉴

参考:

Setting Up User Authentication | X-Pack for the Elastic Stack [5.6] | Elastic 

Java Client and Security | X-Pack for the Elastic Stack [5.6] | Elastic 

Built-in Roles | X-Pack for the Elastic Stack [5.6] | Elastic

Elasticsearch密码设置及其后续问题解决_这个名字还中的博客-CSDN博客_elasticsearch设置密码

Elasticsearch+X-pack和Java Transport方式连接_AllenAlbert的博客-CSDN博客_x-pack-transport

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐