如何用Python SDK创建Azure服务主体?遇azure-graphrbac弃用等问题
使用Python SDK创建Azure服务主体的正确方式
弃用说明
azure-graphrbac SDK已被官方弃用,目前推荐使用Microsoft Graph Python SDK来管理Azure AD服务主体,这是官方支持的最新方案。
步骤1:安装依赖包
pip install msgraph-core azure-identity
步骤2:配置权限
确保你的身份凭据(如本地开发的DefaultAzureCredential)拥有对应的权限:
- 应用程序权限:
Application.ReadWrite.All(允许创建/管理服务主体) - 委派权限:
Directory.AccessAsUser.All(需用户交互授权)
步骤3:代码示例(创建服务主体)
以下代码使用DefaultAzureCredential获取授权,通过Microsoft Graph SDK创建服务主体:
from azure.identity import DefaultAzureCredential from msgraph import GraphServiceClient from msgraph.generated.models.service_principal import ServicePrincipal from datetime import datetime, timedelta # 初始化Graph客户端 credential = DefaultAzureCredential() client = GraphServiceClient(credential) # 定义服务主体参数(需关联已存在的应用注册ID) app_registration_id = "你的应用程序(客户端)ID" service_principal = ServicePrincipal( app_id=app_registration_id, display_name="自定义服务主体名称", description="用于自动化任务的服务主体" ) # 创建服务主体(异步调用) result = await client.service_principals.post(service_principal) print(f"服务主体创建成功,ID: {result.id}")
如果需要为服务主体添加密码凭据:
from msgraph.generated.models.password_credential import PasswordCredential # 定义密码凭据(有效期1年) password_cred = PasswordCredential( display_name="服务主体密码", end_date_time=datetime.utcnow() + timedelta(days=365) ) # 带密码创建服务主体 service_principal = ServicePrincipal( app_id=app_registration_id, display_name="带密码的服务主体", password_credentials=[password_cred] ) result = await client.service_principals.post(service_principal) print(f"带密码的服务主体创建成功,密码仅在此处可见:{result.password_credentials[0].secret_text}")
关于你之前的CredentialWrapper问题
你编写的CredentialWrapper适配旧SDK认证逻辑失败的核心原因是资源ID错误:
- 旧
azure-graphrbac依赖Azure AD Graph,资源ID应为https://graph.windows.net/.default,而非Microsoft Graph的https://graph.microsoft.com/.default。
但请注意:即使修正资源ID,旧SDK已不再接收更新,存在安全风险,强烈建议迁移到Microsoft Graph SDK。
内容的提问来源于stack exchange,提问作者pranoy k
相关产品推荐
相关产品推荐

