Elasticsearch 从 7.x 开始提供 API Key 认证机制,用于替代 Basic Auth / Token,适用于服务间调用(尤其是 Agent / 微服务 / 自动化场景)。
1. 前置条件
1.1开启安全功能
1
| xpack.security.enabled=true
|
确保:
- 已设置
elastic 用户密码
- HTTP 接口可访问(9200)
2. 获取 API Key
2.1 基础方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| curl -u elastic:your_password \ -X POST "http://localhost:9200/_security/api_key" \ -H "Content-Type: application/json" \ -d '{ "name": "my-api-key", "expiration": "1d", "role_descriptors": { "my-role": { "cluster": ["monitor"], "index": [ { "names": ["*"], "privileges": ["read"] } ] } } }'
curl -X POST "http://localhost:9200/_security/service/elastic/kibana/credential/token/kibana" \ -u elastic:321.321 \ -H "Content-Type: application/json"
curl -u elastic:your_password \ -X POST "http://localhost:9200/_security/api_key" \ -H "Content-Type: application/json" \ -d '{ "name": "full-access-key" }'
|
默认继承当前用户权限(elastic = superuser)
1 2 3 4 5 6 7 8 9 10 11 12
| ---
**返回结果解析**
```json { "id": "VuaCfGcBCdbkQm-e5aOx", "name": "my-api-key", "expiration": 1714212345678, "api_key": "tXH3..." }
|
关键字段
| 字段 |
含义 |
| id |
API Key ID |
| api_key |
真正的密钥 |
| expiration |
过期时间(毫秒时间戳) |
Elasticsearch 要求:
Authorization: ApiKey base64(id:api_key)
使用 API Key访问
1 2
| curl -X GET "http://localhost:9200/_cluster/health" \ -H "Authorization: ApiKey <base64值>"
|
4. API Key 生命周期管理
4.1 查询 API Keys
1 2
| curl -u elastic:password \ -X GET "http://localhost:9200/_security/api_key"
|
4.2 删除 API Key
1 2 3 4 5 6
| curl -u elastic:password \ -X DELETE "http://localhost:9200/_security/api_key" \ -H "Content-Type: application/json" \ -d '{ "ids": ["api_key_id"] }'
|