【Azure Developer】Python代码调用Graph API将外部用户添加到组,结果无效,也无错误信息 - LuBu0505/My-Code GitHub Wiki

问题描述

根据Graph API的实例文档,在单个请求中将多个成员添加入组。 代码执行后,无错误消息,但是,用户也没有添加成功。

在单个请求中向组添加多个成员

文档地址 :https://learn.microsoft.com/zh-cn/graph/api/group-post-members?view=graph-rest-1.0&tabs=python

image.png

问题解答

在文档中,对比HTTP / C# / JS / Powershell 代码中的additional  data结构,发现一个不同点:

Python代码示例中,把 [email protected] 错误的写成了 members@odata_bind  image.png

当把 “ _ ” 修改为正确的 “ . " 后,添加操作执行成功!

(Python) 完成实现代码如下:


from azure.identity import ClientSecretCredential
# from msgraph.generated.models.invitation import Invitation
from kiota_authentication_azure.azure_identity_authentication_provider import AzureIdentityAuthenticationProvider
import asyncio
from msgraph.generated.models.unified_role_assignment import UnifiedRoleAssignment

from msgraph import GraphServiceClient, GraphRequestAdapter
from msgraph.generated.models.group import Group
from msgraph.generated.models.reference_create import ReferenceCreate

from msgraph.generated.models.unified_role_assignment import UnifiedRoleAssignment

# Values from app registration
tenant_id = 'xx-x-x-x-xxxx'
client_id = 'xx-x-x-x-xxxx'
client_secret = '***'

# azure.identity.aio
credential = ClientSecretCredential(
   tenant_id=tenant_id,
   client_id=client_id,
   client_secret=client_secret)

scopes = ['https://microsoftgraph.chinacloudapi.cn/.default']
graph_client = GraphServiceClient(credential, scopes)  # type: ignore

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)

async def add_user_to_group():
   request_body = Group(
       additional_data={
           "[email protected]": [
               https://microsoftgraph.chinacloudapi.cn/v1.0/directoryObjects/{id},
               https://microsoftgraph.chinacloudapi.cn/v1.0/directoryObjects/{id},
           ],
       }
   )

   result = await graph_client.groups.by_group_id('xx-x-x-x-xxxx').patch(request_body)

   if result:
       print(result)

asyncio.run(add_user_to_group())

参考资料

在单个请求中向组添加多个成员:https://learn.microsoft.com/zh-cn/graph/api/group-post-members?view=graph-rest-1.0&tabs=python

当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!