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

如何通过Python API以编程方式获取Azure服务主体的object_id?

如何通过Python编程获取Azure服务主体的Object ID

方法一:使用Azure Management SDK(azure-mgmt-graphrbac)

前置准备

安装所需依赖包:

pip install azure-mgmt-graphrbac azure-identity

代码实现

通过服务主体的应用ID(Client ID)查询对应的Object ID:

from azure.identity import DefaultAzureCredential
from azure.mgmt.graphrbac import GraphRbacManagementClient

# 替换为你的租户ID和应用ID
TENANT_ID = "your-tenant-id"
CLIENT_ID = "your-service-principal-client-id"

# 初始化认证和客户端
credential = DefaultAzureCredential()
graph_client = GraphRbacManagementClient(credential, TENANT_ID)

# 根据应用ID过滤查询服务主体
sp_list = list(graph_client.service_principals.list(filter=f"appId eq '{CLIENT_ID}'"))

if sp_list:
    object_id = sp_list[0].object_id
    print(f"服务主体Object ID: {object_id}")
else:
    print("未找到对应的服务主体")

方法二:使用Microsoft Graph API

前置准备

安装所需依赖包:

pip install msgraph-core azure-identity

代码实现

通过Microsoft Graph API查询服务主体信息:

from azure.identity import DefaultAzureCredential
from msgraph_core import GraphClient

# 替换为你的租户ID和应用ID
TENANT_ID = "your-tenant-id"
CLIENT_ID = "your-service-principal-client-id"

# 初始化认证和Graph客户端
credential = DefaultAzureCredential(tenant_id=TENANT_ID)
graph_client = GraphClient(credential=credential)

# 构造查询请求
query_url = f"/v1.0/servicePrincipals?$filter=appId eq '{CLIENT_ID}'"
response = graph_client.get(query_url)
response.raise_for_status()

sp_data = response.json()
if sp_data.get("value"):
    object_id = sp_data["value"][0]["id"]
    print(f"服务主体Object ID: {object_id}")
else:
    print("未找到对应的服务主体")

注意事项

  • 确保使用的认证账号(或服务主体)拥有Application.Read.All的权限,否则会出现权限不足的错误。
  • DefaultAzureCredential支持多种认证方式(环境变量、Azure CLI、VS Code等),可根据实际场景选择合适的认证方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 00:13:21