DEV Community

Ranjit Rimal
Ranjit Rimal

Posted on

Automate User and Group Creation for Microsoft 365

To automate user and group creation for Microsoft 365 in a third-party app, developers can use the Microsoft Graph API, which provides comprehensive endpoints for identity management. First, register an Azure AD application in the Azure Portal and grant it permissions like User.ReadWrite.All and Group.ReadWrite.All. Authenticate using OAuth 2.0 (client credentials flow for background services or auth code flow for user interactions). Below is an example in Python to get an access token:

python:
import requests

tenant_id = "YOUR_TENANT_ID"
client_id = "YOUR_CLIENT_ID"
client_secret = "YOUR_CLIENT_SECRET"

auth_url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
auth_data = {
"grant_type": "client_credentials",
"client_id": client_id,
"client_secret": client_secret,
"scope": "https://graph.microsoft.com/.default"
}

response = requests.post(auth_url, data=auth_data)
access_token = response.json().get("access_token")
This token will be used in subsequent API calls to create users and groups.

Creating Users Programmatically
Once authenticated, you can create users using the Microsoft Graph /users endpoint. The following example in JavaScript (Node.js) demonstrates creating a new user:

javascript:
const axios = require('axios');

const userData = {
accountEnabled: true,
displayName: "John Doe",
mailNickname: "johndoe",
userPrincipalName: "johndoe@yourdomain.com",
passwordProfile: {
forceChangePasswordNextSignIn: true,
password: "P@ssw0rd123!"
}
};

axios.post('https://graph.microsoft.com/v1.0/users', userData, {
headers: {
'Authorization': Bearer ${access_token},
'Content-Type': 'application/json'
}
})
.then(response => console.log("User created:", response.data))
.catch(error => console.error("Error:", error.response.data));
This will create a new Azure AD user with a temporary password.

Creating and Managing Groups
Microsoft Graph also allows automation of group creation and user assignments. Below is an example in PowerShell using Graph API to create a security group and add a user:

powershell:
$headers = @{
"Authorization" = "Bearer $access_token"
"Content-Type" = "application/json"
}

Create a new group

$groupData = @{
displayName = "Sales Team"
mailEnabled = $false
securityEnabled = $true
mailNickname = "salesteam"
} | ConvertTo-Json

$groupResponse = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/groups" -Method Post -Headers $headers -Body $groupData
$groupId = $groupResponse.id

Add a user to the group

$userToAdd = (Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/users/johndoe@yourdomain.com" -Headers $headers).id
$addMemberUrl = "https://graph.microsoft.com/v1.0/groups/$groupId/members/`$ref"
$memberPayload = @{
"@odata.id" = "https://graph.microsoft.com/v1.0/users/$userToAdd"
} | ConvertTo-Json

Invoke-RestMethod -Uri $addMemberUrl -Method Post -Headers $headers -Body $memberPayload
This script creates a security group and assigns a user to it.

Handling Bulk Operations and Error Management
For bulk user/group creation, batch processing can be implemented using Microsoft Graph’s $batch endpoint. Below is a Python example:

python:
batch_payload = {
"requests": [
{
"id": "1",
"method": "POST",
"url": "/users",
"body": {
"accountEnabled": True,
"displayName": "User 1",
"userPrincipalName": "user1@yourdomain.com",
"passwordProfile": {
"password": "TempP@ss123!",
"forceChangePasswordNextSignIn": True
}
},
"headers": { "Content-Type": "application/json" }
},
{
"id": "2",
"method": "POST",
"url": "/groups",
"body": {
"displayName": "Developers",
"mailEnabled": False,
"securityEnabled": True
},
"headers": { "Content-Type": "application/json" }
}
]
}

response = requests.post(
"https://graph.microsoft.com/v1.0/$batch",
headers={"Authorization": f"Bearer {access_token}"},
json=batch_payload
)
print("Batch response:", response.json())

Error handling should include retries for rate limits (429 Too Many Requests) and validation for duplicate users/groups. By leveraging these APIs, developers can fully automate Microsoft 365 user and group management in third-party applications when you have SME products like Microsoft 365 Business Standard or Enterprise Products like Microsoft 365 E3.

Top comments (0)