python - 使用 DefaultAzureCredential 在本地向 Azure Key Vault 进行身份验证

标签 python azure azure-keyvault azure-sdk-python

我正在尝试运行此'Retrieve a secret from the vault'本地示例(Ubuntu 19.10)从 Azure Key Vault 检索 secret :

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

client = SecretClient(vault_url="https://<<vaultname>>.vault.azure.com",
                      credential=DefaultAzureCredential())

secret = client.get_secret("<<mysecret>>")

但是我收到以下错误:

azure.core.exceptions.ClientAuthenticationError:

No credential in this chain provided a token.

Attempted credentials:

EnvironmentCredential: Incomplete environment configuration. See https://aka.ms/python-sdk-identity#environment-variables for expected environment variables

ImdsCredential: IMDS endpoint unavailable

Please visit the documentation at

https://aka.ms/python-sdk-identity#defaultazurecredential

to learn what options DefaultAzureCredential supports

documentation on Service-to-Service authentication to Key Vault似乎表明我应该能够通过 Azure CLI 进行身份验证,并且我已按照步骤通过 az login 登录,选择适当的订阅(我这样做是为了以防万一,尽管只有一个),并通过 az account get-access-token --resource https://vault.azure.net 验证访问,它确实返回一个 token ,但仍然收到上述错误。

我认为通过 cli 登录后应该能够进行身份验证是错误的吗?

如果是这样,我需要手动设置为 EnvironmentCredential 提供的文档链接中描述的环境变量,我需要为 AZURE_CLIENT_IDAZURE_CLIENT_SECRET

最佳答案

Am I wrong in assuming I should be able to authenticate after logging in via the cli?

您没有看错,在我撰写本文时,azure-identity 的当前预览版 1.4.0b2 是可能实现的。安装完毕后,您的代码在登录 CLI 后就应该可以运行。

... what values do I need to supply for AZURE_CLIENT_ID and AZURE_CLIENT_SECRET?

这些将是服务主体的客户端(或“应用程序”)ID 及其 secret 之一。 azure-keyvault-secrets documentation介绍如何使用 CLI 创建服务主体并配置其对 Key Vault 的访问。

在此简要重申该文档,您可以使用以下命令创建服务主体:

az ad sp create-for-rbac --name http://my-application

从该命令的输出中,“appId”是 AZURE_CLIENT_ID 的值,“password”是 AZURE_CLIENT_SECRET 的值。

然后,授予服务主体对 Key Vault secret 的访问权限:

az keyvault set-policy --name <<vaultname>> --spn $AZURE_CLIENT_ID --secret-permissions get set list delete backup recover restore purge

关于python - 使用 DefaultAzureCredential 在本地向 Azure Key Vault 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61125219/

相关文章:

python - LSTM 自动编码器

python - 使用 Mock 对调用 url 的函数进行单元测试

python - 如何获取我的元素的父元素?

c# - 在上传到 azure blob 存储之前对图像数据进行加密

azure - 在 Windows Azure 帐户中找不到订阅

android - 如何使用 azure pipeline 生成 .AAB 文件并签署 Android 应用程序包

asp.net - Azure KeyVault 突然出现 System.Net.Http.HttpRequestException

python - 如何使用原始数据包在python3.5中嗅探Windows 10中的ospf数据包

azure - 在 PowerShell 中设置 Azure Key Vault 访问策略时出错

azure - Azure Pipeline 模板中的动态变量