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

如何通过Python从Azure企业应用名称获取Application ID

通过Python获取Azure企业应用的Application ID(根据应用名称)

可以通过Microsoft Graph API实现这个需求,以下是具体步骤和代码示例:

前提条件

  • 你的服务主体已被授予Application.Read.All权限(需Azure AD管理员同意)
  • 已安装必要的Python包:
    pip install azure-identity msgraph-sdk
    

代码实现

from azure.identity import ClientSecretCredential
from msgraph import GraphServiceClient

# 替换为你的租户ID、服务主体client ID、密钥
tenant_id = "your-tenant-id"
client_id = "your-service-principal-client-id"
client_secret = "your-service-principal-client-secret"
target_app_name = "你的Azure应用名称"

# 初始化认证凭据
credential = ClientSecretCredential(
    tenant_id=tenant_id,
    client_id=client_id,
    client_secret=client_secret
)

# 初始化Graph客户端
graph_client = GraphServiceClient(credential)

try:
    # 查询匹配应用名称的企业应用(对应Graph中的servicePrincipal)
    result = graph_client.service_principals.get(
        filter=f"displayName eq '{target_app_name}'"
    )

    if result.value:
        # 处理可能的同名应用,这里取第一个结果的id
        app_id = result.value[0].id
        print(f"找到的Application ID: {app_id}")
    else:
        print("未找到匹配名称的企业应用")
except Exception as e:
    print(f"查询出错: {str(e)}")

注意事项

  • 如果存在多个同名的企业应用,代码会返回第一个匹配结果,建议确保应用名称唯一,或者添加更多过滤条件(比如publisherName等)
  • Application.Read.All是应用权限,需要管理员在Azure门户中为服务主体授予该权限并完成同意操作
  • 若要查询的是注册的应用程序(而非企业应用/service principal),可将service_principals替换为applications,权限要求保持一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 11:20:58