Sign in

Check whether a user is there on Azure AD and if the user account status is enabled

There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.
import requests from azure.identity import ClientSecretCredential # Set up Azure AD credentials #tenant_id = 'your-tenant-id' # To be set in the input params #client_id = 'your-client-id' # To be set in the input params #client_secret = 'your-client-secret' # To be set in the input params # Initialize the Azure credentials using Azure's ClientSecretCredential credential = ClientSecretCredential(tenant_id, client_id, client_secret) # Function to check if the user exists and verify if the account is enabled def check_user_account_enabled(user_principal_name): # Construct the Microsoft Graph API URL to retrieve user details url = f"https://graph.microsoft.com/v1.0/users/{user_principal_name}?$select=displayName,accountEnabled" # Obtain an access token from Azure AD access_token = credential.get_token('https://graph.microsoft.com/.default').token # Set the authorization header with the bearer token headers = { 'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json' } # Send a GET request to retrieve user details response = requests.get(url, headers=headers) try: # Check if the user exists (successful response) response.raise_for_status() # Raises HTTPError for bad responses if response.text: # Parse the user data user_data = response.json() display_name = user_data.get("displayName") account_enabled = user_data.get("accountEnabled") if account_enabled is not None: print(f"User '{display_name}' exists. Account is {'enabled' if account_enabled else 'disabled'}.") else: print(f"User '{display_name}' exists, but account status is not set.") else: print("No data returned for user.") except requests.exceptions.HTTPError as e: # Handle case where user does not exist if e.response.status_code == 404: print(f"User '{user_principal_name}' not found in Azure AD.") else: print(f"Error: {e.response.status_code} - {e.response.text}") # Example usage of the function #user_principal_name = "johndoe@yourdomain.onmicrosoft.com" check_user_account_enabled(user_principal_name)
copied