无法向 KeyVault 进行身份验证 - 此链中没有凭据提供令牌

Can't authenticate to KeyVault - No credential in this chain provided a token

我正在尝试使用具有 username/password 身份验证的 DefaultAzureCredential 对象对 Key Vault 进行身份验证,但出现此错误:

[06/10/2020 13:57:37] Exception: ClientAuthenticationError: 
[06/10/2020 13:57:37] No credential in this chain provided a token.
[06/10/2020 13:57:37] Attempted credentials:
[06/10/2020 13:57:37]   EnvironmentCredential: Authentication failed: Unable to find wstrust endpoint from MEX. This typically happens when attempting MSA accounts. More details available here. https://github.com/AzureAD/microsoft-authentication-library-for-python/wiki/Username-Password-Authentication
[06/10/2020 13:57:37] 
[06/10/2020 13:57:37] Please visit the documentation at
[06/10/2020 13:57:37] https://aka.ms/python-sdk-identity#defaultazurecredential
[06/10/2020 13:57:37] to learn what options DefaultAzureCredential supports

我可以确认正在从 local.settings.json:

加载所需的环境变量

相关代码:

def encrypt(text):
    uri = os.environ['KEYVAULT_URI']
    credential = DefaultAzureCredential()
    key_client = KeyClient(vault_url=uri, credential=credential)

    key = key_client.get_key("managed-key")
    crypto_client = CryptographyClient(key, credential=credential)
    plaintext = text.encode()

    return crypto_client.encrypt(EncryptionAlgorithm.rsa_oaep, plaintext)

local.settings.json 看起来像这样:

{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "AzureWebJobsStorage": "{AzureWebJobsStorage}",
    "KEYVAULT_URI": "<keyvault_uri>",
    "AZURE_CLIENT_ID": "<client_id>",
    "AZURE_USERNAME": "<email>",
    "AZURE_PASSWORD": "<password>"
  }
}

写完问题我看了文档,找到了原因。错误跟踪也很清楚:

This typically happens when attempting MSA accounts.

不能为此使用个人 Microsoft 帐户。只有工作和学校帐户可以。

来自Username Password Authentication

By design and policy, the username/password authentication works only for Work and school accounts, but not for Microsoft Accounts (MSA).

我切换到 有秘密的服务主体,它解决了我的问题。

有关 EnvironmentCredential 可用选项的详细信息。

"AZURE_TENANT_ID": "",
"AZURE_CLIENT_ID": "",
"AZURE_CLIENT_SECRET": ""

我发现升级我的 python 包解决了这个问题。

pip install --upgrade azure-identity

我有 1.2.0,升级到 1.4.0。