You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

本地运行Python脚本调用SecretClient读取Azure Key Vault密钥遇认证问题

问题描述

我正尝试编写Python脚本从Azure Key Vault读取密钥,但使用SecretClient类时遇到认证问题。

我的代码如下:

from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient


CREDENTIAL = DefaultAzureCredential()
client = SecretClient(
    vault_url="https://my_vault_name.vault.azure.net/",
    credential=CREDENTIAL
)

secret = client.get_secret('my_secret_name')

遇到的错误如下:

EnvironmentCredential: EnvironmentCredential authentication unavailable. Environment variables are not fully configured.
ManagedIdentityCredential: ManagedIdentityCredential authentication unavailable, no response from the IMDS endpoint.
SharedTokenCacheCredential: The current credential is not configured to acquire tokens for tenant 74******---****-*********62. To enable acquiring tokens for this tenant add it to the additionally_allowed_tenants when creating the credential, or add "" to additionally_allowed_tenants to allow acquiring tokens for any tenant.

我已在Azure门户创建托管身份并为其分配Key Vault的全部权限,也尝试过以下代码:

CREDENTIAL = azure.identity.ManagedIdentityCredential(managed_identity_client_id='my_managed_identity_client_id')

以及

CREDENTIAL = ManagedIdentityCredential()

但仍出现相同的ManagedIdentityCredential错误。

注:我在本地机器运行代码,且使用DefaultAzureCredential上传Blob、列出资源的脚本可正常运行,仅SecretClient类存在问题。出于安全考虑,不想使用环境变量(脚本将用于生产环境),且我可通过Azure CLI列出密钥,恳请解决思路与建议。

解决思路与建议
  • 明确本地认证逻辑:托管身份(ManagedIdentityCredential)仅适用于Azure云资源(如VM、App Service等),本地机器无法使用该认证方式,直接调用必然失败。
  • 调整DefaultAzureCredential租户配置:错误提示SharedTokenCacheCredential存在租户权限问题,初始化时指定additionally_allowed_tenants参数即可解决:
    # 指定目标租户
    CREDENTIAL = DefaultAzureCredential(additionally_allowed_tenants=["74******-****-****-****-**********62"])
    # 或允许所有租户(多租户场景适用)
    CREDENTIAL = DefaultAzureCredential(additionally_allowed_tenants=["*"])
    
  • 直接使用AzureCliCredential:既然本地Azure CLI能正常读取密钥,可跳过其他认证方式,直接用CLI身份初始化客户端:
    from azure.identity import AzureCliCredential
    from azure.keyvault.secrets import SecretClient
    
    CREDENTIAL = AzureCliCredential()
    client = SecretClient(
        vault_url="https://my_vault_name.vault.azure.net/",
        credential=CREDENTIAL
    )
    secret = client.get_secret('my_secret_name')
    
  • 生产环境适配:若脚本后续部署到Azure资源,再切换回ManagedIdentityCredential,确保部署资源已配置对应托管身份,且该身份被授予Key Vault的Secret Reader权限(遵循最小权限原则,不建议直接给全部权限)。
  • 排查权限差异:确认Blob操作与Key Vault操作使用的是同一租户、同一身份权限,检查Key Vault访问策略中是否正确添加了你的CLI身份(或托管身份),并授予读取密钥的权限。

内容的提问来源于stack exchange,提问作者KingWolin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 15:53:26