使用 python 在 Elasticsearch 中进行 API 密钥身份验证

Cpt*_*les 2 python authentication api key elasticsearch

我希望通过 elasticsearch python 框架找到我的问题的答案。也许我完全失明或做错了什么,但我现在很困惑,找不到合适的答案。

我目前正在尝试使用elasticsearch python 框架建立到我的弹性搜索 API 的连接,我的代码如下所示:

from elasticsearch import Elasticsearch

def create_es_connection(host: str, port: int, api_key_id: str, api_key: str, user: str, pw: str) -> Elasticsearch:
    return Elasticsearch([f"https://{user}:{pw}@{host}:{port}"])
Run Code Online (Sandbox Code Playgroud)

这工作正常。然后我为我的testuser创建了一个 API 密钥,我也将它提供给了上面的函数。我现在正在尝试做类似的事情:Elasticsearch([f"https://{api_key_id}:{api_key}@{host}:{port}"])所以,我想完全省略用户和密码,因为关于这个片段背后的更大项目,我在保存用户/密码凭据时感觉不太好我的项目(甚至可能将其推送到我们的 git 服务器)。迟早,这些凭据必须在某个地方输入,我认为只保存 API 密钥并使用它进行身份验证可能更安全。不幸的是,这并没有像我计划的那样成功,我找不到任何关于如何仅使用 API 密钥进行身份验证的信息。

我究竟做错了什么?事实上,我对此知之甚少,以至于我在这里质疑我的基本理解。谢谢您的回复!

And*_*eas 5

Elasticsearch 的文档展示了如何生成和使用(在页面底部)API 密钥:https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-create-api-key。 html

curl -H "Authorization: ApiKey ..." http://localhost:9200/_cluster/health
Run Code Online (Sandbox Code Playgroud)

-H意思是“标头”,因此要在 Python 中执行相同操作,您需要设置此标头。翻阅 elasticsearch 模块源代码告诉我,您可能只能执行以下操作:

curl -H "Authorization: ApiKey ..." http://localhost:9200/_cluster/health
Run Code Online (Sandbox Code Playgroud)

原因是该**kwargs方法的Elasticsearch.__init__被传递给Transport.__init__,该**kwargs方法的 被传递给Connection.__init__,它接受一个api_keyarg,然后使用 _get_api_key_header_val该 arg 来构造适当的标头。

以下代码显示 api 密钥标头已添加到请求的 HTTP 标头中:

Elasticsearch([f'http://{host}:{port}'], api_key=api_key)
Run Code Online (Sandbox Code Playgroud)

这绝对是应该添加到 Elasticsearch 文档中的内容。


小智 5

我的工作配置是:

es = Elasticsearch(['localhost:9200'], api_key=('DuSkVm8BZ5TMcIF99zOC','2rs8yN26QSC_uPr31R1KJg'))
Run Code Online (Sandbox Code Playgroud)

  • 这对我有用。`api_key` 显然使用 `api_key=('api_key_id', 'api_key')`。这确实应该记录在某处。 (2认同)