azure 使用Python将数据发布到Microsoft Graph

6vl6ewon  于 2023-03-09  发布在  Python
关注(0)|答案(1)|浏览(118)

我想将数据发布到Microsoft Graph API。我已经有了用于此目的的Graph客户端:

def initialize_graph_for_user_auth(config):
     this.settings = config
     client_id = this.settings['clientId']
     tenant_id = this.settings['authTenant']
     graph_scopes = this.settings['graphUserScopes'].split(' ')
     this.device_code_credential = DeviceCodeCredential(client_id, 
     tenant_id = tenant_id)
     this.user_client = 
     GraphClient(credential=this.device_code_credential, 
     scopes=graph_scopes)

现在我想将用户添加到Azure组。调用此命令时,我具有正确的用户ID和组ID。

def add_member_to_group(user_id, group_id):
ensure_graph_for_app_only_auth()`
payload = {'@odata.id': 
f'https://graph.microsoft.com/v1.0/users/{user_id}'}
response = this.app_client.groups[group_id].post(data=payload)
if response.status_code == 204:
    print(f'Successfully added user {user_id} to group 
    {group_id}.')`
else:
    print('Error:', response.content)
eyh26e7m

eyh26e7m1#

若要使用Microsoft Graph API将用户添加到Azure组,可以使用以下代码:

from msgraphcore import GraphSession
from msgraphcore.middleware import AuthenticationProviderMiddleware

def add_member_to_group(user_id, group_id):
    graph_session = GraphSession(AuthenticationProviderMiddleware(
    tDeviceCodeAuthProvider(client_id, tenant_id)))
    url = f"https://graph.microsoft.com/v1.0/groups/{group_id}/members/$ref"
    headers = {"Content-Type": "application/json"}
    data = {"@odata.id": f"https://graph.microsoft.com/v1.0/users/{user_id}"}
    response = graph_session.post(url, headers=headers, json=data)
    if response.status_code == 204:
        print(f'Successfully added user {user_id} to group {group_id}.')
    else:
        print('Error:', response.content)

相关问题