前言
在很久很久以前,一位萌新程序员小明用Docker安装了Elasticsearch,之后很久很久没有在管过了,但偶然的一次对服务器检查发现ES中存在一堆的数据,小明立马意识到ES的服务被他人使用了,急忙关闭了服务并查询如何对ES进行添加鉴权。
技术点
Elasticsearch,Nginx(可选)
实战
第一种:ES启用鉴权
本次ES运行版本为7.17.2,不同的版本可能会存在配置不同,可能需要查询下当前版本的手册较佳。
elasticsearch.yml
对配置文件添加如下配置
http.cors.enabled: true
http.cors.allow-origin: "*"
http.cors.allow-headers: Authorization
xpack.security.enabled: true
xpack.security.transport.ssl.enabled: true
添加配置后重启服务发现再次访问ES服务则需要提示输入账户密码,点击取消会有401的错误提示.
配置密码
配置完上一步,此时服务是不可访问,,因此我们还需要在终端配置密码。
术哥@ubuntu:/usr/share/elasticsearch# elasticsearch-setup-passwords interactive
Initiating the setup of passwords for reserved users elastic,apm_system,kibana,kibana_system,logstash_system,beats_system,remote_monitoring_user.
You will be prompted to enter passwords as the process progresses.
Please confirm that you would like to continue [y/N] y
Enter password for [elastic]:
Reenter password for [elastic]:
Enter password for [apm_system]:
Reenter password for [apm_system]:
Enter password for [kibana_system]:
Reenter password for [kibana_system]:
Enter password for [logstash_system]:
Reenter password for [logstash_system]:
Enter password for [beats_system]:
Reenter password for [beats_system]:
Enter password for [remote_monitoring_user]:
Reenter password for [remote_monitoring_user]:
Changed password for user [apm_system]
Changed password for user [kibana_system]
Changed password for user [kibana]
Changed password for user [logstash_system]
Changed password for user [beats_system]
Changed password for user [remote_monitoring_user]
Changed password for user [elastic]
Change完成后就重启服务,访问ES服务,输入账号elastic
和你设置的密码既可。
第二种:使用Nginx添加Basic鉴权
此方法就比较简单了,不需要得ES内进行配置,则使用Nginx进行端口转发且添加Basic鉴权,就直接上配置文件了。
如何生成鉴权文件可参考上一篇文章【小技巧】为Web再加上一把锁。
配置文件
注意:此配置文件只显示需要改动点,并不能直接复制粘贴使用
steam es{
server 127.0.0.1:9200
}
server {
auth_basic "admin area"; # 启用鉴权
auth_basic_user_file "/etc/nginx/http_auth/.{domain}.pass"; # 指定鉴权文件
location / {
http_proxy es;
}
}
成果
鉴权成功
[图片未上传]
鉴权失败
[图片未上传]
额外的点
Kibana鉴权
由于我们为ES添加了鉴权,因此Kibana这块也需要在配置文件上添加对应配置
[配置中心未找到KEY]
可能会遇到的问题?
ERROR: X-Pack Security is disabled by configuration.
术哥@ubuntu:/usr/share/elasticsearch# elasticsearch-setup-passwords interactive
Unexpected response code [500] from calling GET http://127.0.0.1:9200/_security/_authenticate?pretty
It doesn't look like the X-Pack security feature is enabled on this Elasticsearch node.
Please check if you have enabled X-Pack security in your elasticsearch.yml configuration file.
ERROR: X-Pack Security is disabled by configuration.
你服务压根没重启吧。