【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
当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!