def get_user_groups(auth_token, user_id): url = f"https://graph.microsoft.com/v1.0/users/{user_id}/getMemberGroups" headers = { "Authorization": "Bearer " + auth_token, "Content-Type": "application/json" } response = http.post(url, headers=headers, data={'securityEnabledOnly': False}) if response.ok: return response.json['value'] raise AzureError(f'get_user_groups failed with {response.code} - {response.text}')
def group_add_member(auth_token, group_id, user_id): url = "https://graph.microsoft.com/v1.0/groups/{}/members/$ref".format(group_id) headers = { "Authorization": "Bearer " + auth_token, "Content-Type": "application/json" } data = { '@odata.id': f'https://graph.microsoft.com/v1.0/users/{user_id}' } response = http.post(url, headers=headers, data=data) if response.status_code == 204: return True raise AzureError(f'group_add_member failed with {response.code} - {response.text}')
def assign_group_to_app_role(auth_token, group_id, app_role_id): url = "https://graph.microsoft.com/v1.0/groups/{0}/appRoleAssignments".format(group_id) headers = { "Authorization": "Bearer " + auth_token, "Content-Type": "application/json" } data = { 'principalId': group_id, 'resourceId': SERVICE_ID, 'appRoleId': app_role_id } response = http.post(url, headers=headers, data=data) if response.ok: return response.json raise AzureError(f'assign_group_to_app_role failed with {response.code} - {response.text}')
def create_group(auth_token, name, desc): url = "https://graph.microsoft.com/v1.0/groups" headers = { "Authorization": "Bearer " + auth_token, "Content-Type": "application/json" } data = { 'description': desc, 'displayName': name, 'mailEnabled': False, 'mailNickname': str(uuid.uuid4()), 'securityEnabled': True } response = http.post(url, headers=headers, data=data) if response.status_code == 201: return response.json raise AzureError(f'create_group failed with {response.code} - {response.text}')
def get_bearer_token(resource): if not TENANT_ID or not CLIENT_ID or not CLIENT_SECRET: raise AzureError('Missing authentication.') url = "https://login.microsoftonline.com/{0}/oauth2/token".format(TENANT_ID) payload = { 'grant_type': 'client_credentials', 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'resource': resource } response = http.post(url, data=payload, headers={'Content-Type': 'application/x-www-form-urlencoded'}) if response.ok: log.debug('Authentication response: %s', response.text) if 'access_token' not in response.json: raise AzureError(f'Unexpected response in get_bearer_token - {response}') # return actual token return response.json['access_token'] raise AzureError(f'get_bearer_token failed with {response.code} - {response.text}')