基于'elasticsearch-service-tokens create elastic/kibana kibana'发现容器销毁重建后Service Account Token失效问题排查

错误日志

1
2
3
security_exception:
failed to authenticate service account [elastic/kibana]
with token name [kibana]

认证token无效


1. 先理解 Kibana Token原理

你现在使用的是

1
ELASTICSEARCH_SERVICEACCOUNTTOKEN=${ES_TOKEN}

它对应的是service account: elastic/kibana

token 有两种存储方式:

第一种(推荐)

使用 API 创建

1
POST /_security/service/elastic/kibana/credential/token/kibana

这种 token 会保存在.security索引里面。只要data/没有删除,token 永远不会失效。


第二种

使用

1
bin/elasticsearch-service-tokens create elastic/kibana kibana

创建这种 token 保存在config/service_tokens文件,Docker 官方镜像很多人都是这种,如果容器删掉重新创建config/service_tokens没挂载token 就没了。而 Kibana 还拿着旧 token于是:security_exception。


2. 判断你是哪一种

进入 ES: docker exec -it elasticsearch bash

看看cat config/service_tokens,有没有elastic/kibana/kibana = AAEAA…

存在则说明是基于命令创建token


2.1基于token认证检查是否有效

执行

1
2
3
curl \
-u elastic:321.321 \
http://localhost:9200/_security/_authenticate

确认 ES 正常,然后:

1
2
3
curl \
-H "Authorization: Bearer AAEAA...." \
http://localhost:9200/_security/_authenticate

如果返回

1
2
3
4
5
{
"error": {
"type":"security_exception"
}
}

说明

ES 根本不认识这个 token。


2.2如何确认是不是 token 丢了

进入 ES:

1
2
3
curl \
-u elastic:321.321 \
http://localhost:9200/_security/service/elastic/kibana/credential

正常会返回:

1
2
3
4
5
6
7
8
9
{
"service_account":"elastic/kibana",
"count":1,
"tokens":[
{
"name":"kibana"
}
]
}

3.基于接口形式认证信息存储.security索引中

重新生成一个。

1
2
3
4
curl \
-u elastic:321.321 \
-X POST \
http://localhost:9200/_security/service/elastic/kibana/credential/token/kibana

返回:

1
2
3
4
5
6
7
{
"created":true,
"token":{
"name":"kibana",
"value":"AAEAA...."
}
}

替换

.env
ES_TOKEN=AAEAA...

重启

1
docker compose up -d