You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
importasynciofromazure.identityimportClientSecretCredentialfrommsgraphimportGraphServiceClient# Create a credential object. Used to authenticate requestscredential=ClientSecretCredential(
tenant_id='TENANT_ID',
client_id='CLIENT_ID',
client_secret='CLIENT_SECRET'
)
scopes= ['https://graph.microsoft.com/.default']
# Create an API client with the credentials and scopes.client=GraphServiceClient(credentials=credential, scopes=scopes)
2. GET A SPECIFIC USER (GET /users/{id | userPrincipalName})
asyncdefget_user():
user=awaitclient.users.by_user_id('USER_ID').get()
ifuser:
print(user.user_principal_name, user.display_name, user.id)
asyncio.run(get_user())
# LIST ALL TRANSITIVE MEMBERSHIPS OF A USER (GET /users/{id}/transitiveMemberOf)asyncdefget_memberships():
memberships=awaitclient.users.by_user_id('USER_ID').transitive_member_of.get()
ifmembershipsandmemberships.value:
formembershipinmemberships.value:
obj=awaitclient.directory_objects.by_directory_object_id(membership.id).get()
ifobjandobj.odata_type=='#microsoft.graph.group':
group=awaitclient.groups.by_group_id(obj.id).get()
ifgroup:
print(group.id, group.group_types, group.display_name, group.mail)
asyncio.run(get_memberships())
3. SEARCH USER BY NAME (GET /users/$search?=)
importasynciofromazure.identityimportAzureCliCredentialfrommsgraphimportGraphServiceClientfrommsgraph.generated.users.users_request_builderimportUsersRequestBuilderasyncdeffind_user(user_name: str, client: GraphServiceClient) ->None:
# The query used here is the same when searching for users in Azure AD via web consolequery_params=UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
search=[
f'("displayName:{user_name}" OR "mail:{user_name}" OR "userPrincipalName:{user_name}" OR "givenName:{user_name}" OR "surName:{user_name}" OR "otherMails:{user_name}")'
],
)
request_configuration= (
UsersRequestBuilder.UsersRequestBuilderGetRequestConfiguration(
query_parameters=query_params,
)
)
request_configuration.headers.add("ConsistencyLevel", "eventual")
response=awaitclient.users.get(request_configuration=request_configuration)
ifresponse.value:
user=response.value[0]
print(
f"Found user for {user_name} in the Azure AD with user principal name {user.user_principal_name} and display name {user.display_name}"
)
else:
print(f"{user_name} user in the Azure AD not found")
defmain():
# Use cli credentials to authenticate against Azure# Before running script do `az login`credential=AzureCliCredential()
scopes= ["https://graph.microsoft.com/.default"]
client=GraphServiceClient(credentials=credential, scopes=scopes)
asyncio.run(find_user("john", client))
main()