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

如何使用用户分配托管标识认证Azure DevOps Python API(含两种场景)

使用用户分配托管标识认证Azure DevOps Python API

前提条件

  • 已为你的Azure资源(如VM、App Service等)配置用户分配托管标识
  • 已将该托管标识添加到Azure DevOps组织中,并分配了所需权限(如项目集合管理员、项目贡献者等)

一、使用Azure DevOps Python SDK(官方包装器)认证

步骤1:安装依赖包

pip install azure-devops azure-identity

步骤2:编写认证代码

from azure.devops.connection import Connection
from azure.identity import ManagedIdentityCredential
from msrest.authentication import BasicAuthentication

# 替换为你的用户分配MSI客户端ID
USER_ASSIGNED_MSI_CLIENT_ID = "xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
# 替换为你的Azure DevOps组织URL
ORG_URL = "https://dev.azure.com/your-organization-name"

# 通过用户分配MSI获取Azure DevOps访问令牌
# 目标资源ID固定为Azure DevOps的服务ID:499b84ac-1321-427f-aa17-267ca6975798
credential = ManagedIdentityCredential(client_id=USER_ASSIGNED_MSI_CLIENT_ID)
token = credential.get_token("499b84ac-1321-427f-aa17-267ca6975798/.default")

# 构造认证对象并创建DevOps连接
auth = BasicAuthentication("", token.token)
connection = Connection(base_url=ORG_URL, creds=auth)

# 示例:调用SDK接口获取项目列表
core_client = connection.clients.get_core_client()
projects = core_client.get_projects()
for project in projects:
    print(f"项目名称:{project.name}")

二、不使用Python包装器(直接调用REST API)

步骤1:安装依赖包

pip install azure-identity requests

步骤2:编写认证及API调用代码

import requests
from azure.identity import ManagedIdentityCredential

# 替换为你的用户分配MSI客户端ID
USER_ASSIGNED_MSI_CLIENT_ID = "xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
# 替换为你的Azure DevOps组织URL
ORG_URL = "https://dev.azure.com/your-organization-name"
# 按需调整API版本
API_VERSION = "7.1-preview.4"

# 获取Azure DevOps访问令牌
credential = ManagedIdentityCredential(client_id=USER_ASSIGNED_MSI_CLIENT_ID)
token = credential.get_token("499b84ac-1321-427f-aa17-267ca6975798/.default")

# 构造请求头
headers = {
    "Authorization": f"Bearer {token.token}",
    "Content-Type": "application/json"
}

# 示例:调用REST API获取项目列表
response = requests.get(
    f"{ORG_URL}/_apis/projects?api-version={API_VERSION}",
    headers=headers
)
response.raise_for_status()  # 捕获请求错误
projects = response.json()
for project in projects["value"]:
    print(f"项目名称:{project['name']}")

关键注意事项

  • 确保用户分配托管标识已在Azure DevOps组织中被授予正确权限:在Azure DevOps组织设置的「用户」页面中,添加该MSI的客户端ID作为用户,分配对应角色
  • 令牌的目标资源ID499b84ac-1321-427f-aa17-267ca6975798是Azure DevOps服务的固定ID,不可修改
  • 若在本地测试,需确保环境支持托管标识(如Azure VM/容器实例中),本地开发可使用Azure CLI登录模拟MSI环境

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:13:11