Python AzureAppConfiguration SDK和Azure CLI SDK拒绝身份验证

iih3973s  于 2023-05-07  发布在  Python
关注(0)|答案(1)|浏览(129)

我在验证Python环境时遇到了各种各样的问题。我的最终目标是使用Azure AppConfiguration SDK从Azure中的AppConfig服务读取值。但现在我在第一关就失败了。
仅供参考,我正在使用VS Code(以管理员身份运行)在Windows 11机器上运行所有这些。我已安装最新的Azure CLI。
我的Azure应用配置脚本如下:

from azure.identity import DefaultAzureCredential
from azure.appconfiguration import AzureAppConfigurationClient

appCfgUrl = os.environ["AppConfigUrl"]
credential = DefaultAzureCredential()
client = AzureAppConfigurationClient(appCfgUrl, credential)
value = client.get_configuration_setting(configKey)

但这会导致错误:

DefaultAzureCredential failed to retrieve a token from the included credentials.
Attempted credentials:
    EnvironmentCredential: Authentication failed: AADSTS70011: The provided request must include a 'scope' input parameter. The provided value for the input parameter 'scope' is not valid. The scope https://Endpoint=https://foo.azconfig.io;Id=XXXXXX;Secret=YYYYYY=/.default is not valid.

因此,我认为AppConfig SDK可能有问题,或者我实现它的方式有问题,所以我想我应该尝试直接使用Authenticating Azure CLI with Python SDK建议的以下代码直接连接到Azure CLI

import os
from azure.cli.core import get_default_cli

az_cli = get_default_cli()

clientId = os.environ["AZURE_CLIENT_ID"]
clientSecret = os.environ["AZURE_CLIENT_SECRET"]
tenantId = os.environ["AZURE_TENANT_ID"]

az_cli.invoke(['login', '--service-principal', 
               '-u', clientId, 
               '-p', clientSecret,
               '--tenant',tenantId])

但是,这只会导致错误消息

No module named 'azure.cli.command_modules'.
'login' is misspelled or not recognized by the system.

我尝试了 * pipinstallazure.cli.core* 和 * pipinstallazure-cli *
我还在我的机器上升级了Azure CLI。我可以在Bash和PowerShell中成功地对Azure CLI进行身份验证,没有任何问题-我还有另一个.NET C#项目使用Azure CLI,没有任何问题。
在这一点上,我真的撕裂我的头发了。我尝试过为服务主体使用硬编码的值,以及使用本地定义的环境变量-但它们都不起作用。
如前所述,我已经在.NET中的两个单元测试、一个Azure Function App和一个Azure Web App中完成了所有这些工作,没有遇到任何问题,但在Python中完成这些工作似乎遇到了困难。

ecfdbz9o

ecfdbz9o1#

从附加的错误消息中可以看出,您的配置存储的完整连接字符串已保存在“AppConfigUrl”环境变量中。要使用Azure凭据进行身份验证,appCfgUrl变量应该仅为商店的端点,即https://your-store-name.azconfig.io。要使用连接字符串进行身份验证,您可以按如下所示创建客户端:

client = AzureAppConfigurationClient.from_connection_string(<AZURE-APPCONFIGURATION-CONNECTION-STRING>)

更多信息和示例可以在这里找到。希望这能帮上忙。
顺便说一下,你也可以使用App Configuration Python Provider,它使你能够像Python字典一样访问和使用你的配置设置。

相关问题