Skip to content

Instantly share code, notes, and snippets.

@earthquakesan
Created September 19, 2023 20:33
Show Gist options
  • Select an option

  • Save earthquakesan/92a92ddcc29c064ab3255c983ef2d168 to your computer and use it in GitHub Desktop.

Select an option

Save earthquakesan/92a92ddcc29c064ab3255c983ef2d168 to your computer and use it in GitHub Desktop.
Search for user in Azure AD using username - the same behaviour as in the web console
import asyncio
from azure.identity import AzureCliCredential
from msgraph import GraphServiceClient
from msgraph.generated.users.users_request_builder import UsersRequestBuilder
async def get_user(user_name: str, client: GraphServiceClient) -> None:
# The query used here is the same when searching for users in Azure AD via web console
query_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, headers={"ConsistencyLevel": "eventual"}
)
)
response = await client.users.get(request_configuration=request_configuration)
if response.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")
def main():
# Create a credential object. Used to authenticate requests
credential = AzureCliCredential()
scopes = ["https://graph.microsoft.com/.default"]
client = GraphServiceClient(credentials=credential, scopes=scopes)
asyncio.run(get_user("john", client))
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment