agent: |
HktZ2kS2ydqwceT0Bs6GCreate User in Azure AD (Microsoft Entra ID now)
Create User in Azure AD (Microsoft Entra ID now)
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.
Create a new user account in Azure Active Directory using Microsoft Entra ID Now. This involves setting up basic user details like name, email, and initial group memberships.
inputs
outputs
import requests
from azure.identity import ClientSecretCredential
# Set up Azure AD credentials
tenant_id = 'your-tenant-id'
client_id = "your-client-id"
client_secret = "your-client-secret"
# Use environment variables or secure vaults/key management solutions to handle secrets safely
# import os
# tenant_id = os.getenv("AZURE_TENANT_ID")
# client_id = os.getenv("AZURE_CLIENT_ID")
# client_secret = os.getenv("AZURE_CLIENT_SECRET")
# Define the domain and other user attributes
domain = "yashyadav34gmail.onmicrosoft.com"
user_name = "johndoe"
display_name = "John Doe"
job_title = "Software Developer"
email = f"{user_name}@example.com"
mobile_phone = "+1234567890"
office_location = "Building 1, Room 101"
preferred_language = "en-US"
password = "initialPassword123!"
force_change_password = True
credential = ClientSecretCredential(tenant_id, client_id, client_secret)
# Define the user with detailed information
user_data = {
"accountEnabled": True,
"displayName": display_name,
"mailNickname": user_name,
"userPrincipalName": f"{user_name}@{domain}",
"givenName": "John", # Static givenName for demonstration; adjust as necessary
"surname": "Doe", # Static surname for demonstration; adjust as necessary
"jobTitle": job_title,
"mail": email,
"mobilePhone": mobile_phone,
"officeLocation": office_location,
"preferredLanguage": preferred_language,
"passwordProfile": {
"forceChangePasswordNextSignIn": force_change_password,
"password": password
}
}
# Create the user in Azure AD
url = 'https://graph.microsoft.com/v1.0/users'
try:
access_token = credential.get_token('https://graph.microsoft.com/.default').token
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
response = requests.post(url, headers=headers, json=user_data)
response.raise_for_status()
# Print raw JSON output
print("Raw JSON response:")
print(response.json())
print()
# Extract data for table display
user_info = response.json()
print("User created successfully:")
print(f"{'Attribute':<20} | {'Value'}")
print("-" * 60)
for key in ['id', 'displayName', 'userPrincipalName', 'mail', 'mobilePhone', 'officeLocation', 'givenName', 'surname', 'jobTitle', 'preferredLanguage']:
print(f"{key:<20} | {user_info.get(key, 'Not assigned')}")
except requests.exceptions.HTTPError as e:
print("HTTP request failed:", e, response.text)
except Exception as e:
print("An error occurred:", e)
"""
# Sample Output
Raw JSON response:
{'@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#users/$entity', 'id': '7f16743b-2b12-4697-b065-d9637a1b30e7', 'businessPhones': [], 'displayName': 'John Doe', 'givenName': 'John', 'jobTitle': 'Software Developer', 'mail': 'johndoe@example.com', 'mobilePhone': '+1234567890', 'officeLocation': 'Building 1, Room 101', 'preferredLanguage': 'en-US', 'surname': 'Doe', 'userPrincipalName': 'johndoe@yashyadav34gmail.onmicrosoft.com'}
User created successfully:
Attribute | Value
------------------------------------------------------------
id | 7f16743b-2b12-4697-b065-d9637a1b30e7
displayName | John Doe
userPrincipalName | johndoe@yashyadav34gmail.onmicrosoft.com
mail | johndoe@example.com
mobilePhone | +1234567890
officeLocation | Building 1, Room 101
givenName | John
surname | Doe
jobTitle | Software Developer
preferredLanguage | en-US
"""
copied