Spring Cloud Config Server对接HashiCorp Vault无法获取密钥问题
问题描述
使用Spring Cloud Config Server对接HashiCorp Vault作为后端存储时,无法获取已配置的密钥。直接请求Vault API可正常获取数据,怀疑问题出在Config Server侧。
操作步骤
配置并启动Config Server
bootstrap.yml配置如下:spring: application: name: config-server profiles: active: # this value set can refer to : https://docs.spring.io/spring-cloud-config/docs/2.2.x/reference/html/#vault-backend - vault cloud: config: server: vault: port: "8200" host: "127.0.0.1" kv-version: 2 server: port: 8071启动Vault容器
执行命令启动Vault 1.13.2版本的Docker容器:docker run --cap-add=IPC_LOCK -d -p 8200:8200 --name vault -e 'VAULT_DEV_ROOT_TOKEN_ID=myroot' -e 'VAULT_DEV_LISTEN_ADDRESS=0.0.0.0:8200' vault配置Vault密钥
- 通过Web UI登录(token:myroot),启用v2版本的kv密钥引擎,路径设置为
licensing-service; - 在密钥路径
default下添加密钥:key为license.vault.property,value为Welcome to Vault。
- 通过Web UI登录(token:myroot),启用v2版本的kv密钥引擎,路径设置为
请求Config Server
执行curl命令:curl -X "GET" "http://localhost:8071/licensing-service/default" -H "X-Config-Token: myroot"响应结果为空的propertySources:
{"name":"licensing-service","profiles":["default"],"label":null,"version":null,"state":null,"propertySources":[]}%
原因分析及解决方案
1. 密钥存储路径与Config Server默认规则不匹配
Spring Cloud Config Server对接Vault kv v2时,默认会按照{backend}/data/{application}/{profile}的路径查找密钥。你当前将kv引擎路径设为licensing-service,但密钥存在licensing-service/data/default,而Config Server实际会去licensing-service/data/licensing-service/default查找,路径不匹配导致无法读取。
解决方式:
- 调整Vault密钥存储路径:将密钥存入
licensing-service/data/licensing-service/default; - 或修改Config Server配置,指定
application-name匹配你的存储路径:spring: cloud: config: server: vault: backend: licensing-service application-name: licensing-service
2. 版本兼容性问题
你使用的Spring Cloud Config 2.2.x版本发布时间较早,对Vault 1.13.2版本的kv v2支持可能存在兼容性问题,部分新特性或接口变化未被适配。
解决方式:
升级Spring Cloud Config到2.4.x及以上版本,确保与Vault 1.13.x版本兼容。
3. Token传递验证
虽然请求头携带了X-Config-Token,需确认Config Server是否正确将token传递给Vault。可开启Config Server的debug日志,查看Vault请求的认证细节,排查是否存在token未被正确解析或传递的情况。
内容的提问来源于stack exchange,提问作者Flamer

