在 Elasticsearch 8 版本中如何进行API认证的步骤
首先
您是否遇到了在 Elasticsearch 升级到版本8后无法执行 curl 命令的情况?
$ curl -s http://localhost:9200/
执行结果
{
"error":{
"root_cause":[
{
"type":"security_exception",
"reason":"missing authentication credentials for REST request [/]",
"header":{
"WWW-Authenticate":[
"Basic realm=\"security\" charset=\"UTF-8\"",
"ApiKey"
]
}
}
],
"type":"security_exception",
"reason":"missing authentication credentials for REST request [/]",
"header":{
"WWW-Authenticate":[
"Basic realm=\"security\" charset=\"UTF-8\"",
"ApiKey"
]
}
},
"status":401
}
这次是关于解决这个问题的方法。
验证环境
-
- Ubuntu 22.04.2 LTS
lsb_release -a1
Elasticsearch 8.10.3
curl 7.81.0-1ubuntu1.14
apt list –installed | grep curl2
Python 3.10.12
python3 -V
解决方案
解决的方法是输入Elasticsearch的用户名和密码。
以下是为不知道Elasticsearch密码的人准备的密码重置方法3。
Elasticsearch密码重置
重置Elasticsearch密码的命令
$ sudo /usr/share/elasticsearch/bin/elasticsearch-reset-password -u elastic
执行结果
This tool will reset the password of the [elastic] user to an autogenerated value.
The password will be printed in the console.
Please confirm that you would like to continue [y/N]y
Password for the [elastic] user successfully reset.
New value: <新しいパスワード>
$ export ELASTIC_PASSWORD="<新しいパスワード>"
请注意:一旦退出shell,export的变量将消失。
确认
使用curl进行连通性测试。
$ curl -u elastic:$ELASTIC_PASSWORD -s http://localhost:9200/
执行结果
{
"name" : "<ホスト名>",
"cluster_name" : "elasticsearch",
"cluster_uuid" : "<クラスターのID>",
"version" : {
"number" : "8.10.3",
"build_flavor" : "default",
"build_type" : "deb",
"build_hash" : "c63272efed16b5a1c25f3ce500715b7fddf9a9fb",
"build_date" : "2023-10-05T10:15:55.152563867Z",
"build_snapshot" : false,
"lucene_version" : "9.7.0",
"minimum_wire_compatibility_version" : "7.17.0",
"minimum_index_compatibility_version" : "7.0.0"
},
"tagline" : "You Know, for Search"
}
通过使用curl命令,您可以在Elasticsearch中使用该API。
用Python进行确认(额外)
我将尝试使用Python在requests模块中执行与curl相同的操作,进行基本认证4。
import requests
from requests.auth import HTTPBasicAuth
import json
elastic_url = 'http://localhost:9200/'
# Basic Authentication
# https://requests.readthedocs.io/en/latest/user/authentication/
basic = HTTPBasicAuth('elastic', '<新しいパスワード>')
headers = {
'Content-Type': 'application/json',
}
response = requests.get(elastic_url, auth=basic, headers=headers)
print(json.dumps(response.json(), indent=4))
$ python3 elastic_requests.py
执行后会得到与curl相同的结果。
执行结果
{
"name" : "<ホスト名>",
"cluster_name" : "elasticsearch",
"cluster_uuid" : "<クラスターのID>",
"version" : {
"number" : "8.10.3",
"build_flavor" : "default",
"build_type" : "deb",
"build_hash" : "c63272efed16b5a1c25f3ce500715b7fddf9a9fb",
"build_date" : "2023-10-05T10:15:55.152563867Z",
"build_snapshot" : false,
"lucene_version" : "9.7.0",
"minimum_wire_compatibility_version" : "7.17.0",
"minimum_index_compatibility_version" : "7.0.0"
},
"tagline" : "You Know, for Search"
}
请参考以下网站
使用Docker安装Elasticsearch | Elasticsearch Guide 8.11 | Elastic ↩
身份验证 — Requests 2.31.0 文档 ↩