【Azure Developer】分享一段Python代码调用Graph API创建用户的示例
问题描述
在Azure门户(Create new user - Microsoft Azure 由世纪互联运营)中添加新用户,如果想通过代码来实现,有没有示例代码参考呢?
问题解答
示例代码
from azure.identity import AzureAuthorityHosts from azure.identity.aio import ClientSecretCredential from kiota_authentication_azure.azure_identity_authentication_provider import AzureIdentityAuthenticationProvider from msgraph import GraphServiceClient, GraphRequestAdapter from msgraph.generated.models.password_profile import PasswordProfile from msgraph.generated.models.user import User tenant_id = 'xxxxxxxxxxxxxxxxx' client_id = 'xxxxxxxxxxxxxxxxx' client_secret = 'xxxxxxxxxxxxxxxxx' credential = ClientSecretCredential( tenant_id=tenant_id, client_id=client_id, client_secret=client_secret, authority=AzureAuthorityHosts.AZURE_CHINA ) scopes = ['https://microsoftgraph.chinacloudapi.cn/.default'] auth_provider = AzureIdentityAuthenticationProvider(credential, scopes=scopes) request_adapter = GraphRequestAdapter(auth_provider) request_adapter.base_url = "https://microsoftgraph.chinacloudapi.cn/v1.0/" graph_client = GraphServiceClient(request_adapter=request_adapter) request_body = User( account_enabled = True, display_name = "test", mail_nickname = "test", user_principal_name = "xxxxxxxx@xxxxxxxxxxxxxxxxxx", password_profile = PasswordProfile( force_change_password_next_sign_in = True, password = "xxxxxxxxxxxxxxxxxxxxx", ), ) async def create_user(): result = await graph_client.users.post(request_body) return result import asyncio asyncio.run(create_user())
注意:
1:指定 ClientSecretCredential 中 authority=AzureAuthorityHosts.AZURE_CHINA
2:指定 scopes = ['https://microsoftgraph.chinacloudapi.cn/.default']
3:在中国区Azure上创建User,所以必须重新定义Base_url 为 https://microsoftgraph.chinacloudapi.cn/v1.0/
参考资料
Microsoft Graph API Create User : https://learn.microsoft.com/zh-cn/graph/api/user-post-users?view=graph-rest-1.0&tabs=python#request-body
当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
2021-12-03 【Azure 存储服务】关于对Azure Storage Account 的 Folder 权限管理和设定