Azure DevOps Python脚本认证问题:DefaultAzureCredential报错及方案咨询
我正在创建与Azure DevOps交互的Python脚本,不想使用PAT进行认证。使用azure.identity中的DefaultAzureCredential时,出现错误:'DefaultAzureCredential' object has no attribute 'signed_session'。
代码示例:
from azure.identity import DefaultAzureCredential from azure.devops.connection import Connection credential = DefaultAzureCredential() connection = Connection(base_url="https://dev.azure.com/org_name", creds=credential) core_client = connection.clients.get_core_client() projects = core_client.get_projects()
我找到另一种方法可以运行,但注意到官方推荐使用azure.identity而非azure.common.credentials.get_azure_cli_credentials()。
代码示例:
from azure.common.credentials import get_azure_cli_credentials from azure.devops.connection import Connection credential = get_azure_cli_credentials()[0] connection = Connection(base_url="https://dev.azure.com/org_name", creds=credential) core_client = connection.clients.get_core_client() projects = core_client.get_projects()
该方法不适用于azure-cli-core>=2.21.0(2021年3月发布),现在推荐使用azure-identity和AzureCliCredential进行认证。
请问我使用DefaultAzureCredential的方式是否有误?或者有没有更好的方案?
解决方法
问题原因
Azure DevOps的Connection类目前不直接支持azure.identity库中的新式凭据类型,它期望的是带有signed_session方法的旧式凭据对象,这就是DefaultAzureCredential报错的核心原因。
正确实现方案
我们需要通过azure.identity获取访问令牌,再将其转换为Connection类能识别的BasicAuthentication对象来完成认证。
方案1:使用AzureCliCredential(适配新版Azure CLI)
from azure.identity import AzureCliCredential from azure.devops.connection import Connection from msrest.authentication import BasicAuthentication # 初始化Azure CLI凭据 credential = AzureCliCredential() # 获取Azure DevOps服务的访问令牌,资源固定为https://app.vssps.visualstudio.com/ token = credential.get_token("https://app.vssps.visualstudio.com/.default") # 转换为Connection能识别的认证对象(用户名留空,令牌作为密码) basic_auth = BasicAuthentication("", token.token) # 建立连接并调用API connection = Connection(base_url="https://dev.azure.com/org_name", creds=basic_auth) core_client = connection.clients.get_core_client() projects = core_client.get_projects() # 示例:遍历打印项目名称 for project in projects: print(project.name)
方案2:使用DefaultAzureCredential(支持多环境自动认证)
如果需要在本地、服务器、Azure托管环境等多种场景下自动适配认证方式,推荐用DefaultAzureCredential:
from azure.identity import DefaultAzureCredential from azure.devops.connection import Connection from msrest.authentication import BasicAuthentication credential = DefaultAzureCredential() # 同样获取Azure DevOps的访问令牌 token = credential.get_token("https://app.vssps.visualstudio.com/.default") basic_auth = BasicAuthentication("", token.token) connection = Connection(base_url="https://dev.azure.com/org_name", creds=basic_auth) core_client = connection.clients.get_core_client() projects = core_client.get_projects()
原理说明
Azure DevOps REST API支持Bearer令牌认证,通过BasicAuthentication对象传递时,只需将用户名设为空字符串,密码填入获取到的访问令牌,即可完成身份验证。这种方式既符合官方推荐的azure.identity库使用规范,又能完美适配Azure DevOps的Connection类。
内容的提问来源于stack exchange,提问作者Marcin Słowikowski

