Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darrenjrobinson/deab0ea0369f9d391e0eacbc883c5ba0 to your computer and use it in GitHub Desktop.
Save darrenjrobinson/deab0ea0369f9d391e0eacbc883c5ba0 to your computer and use it in GitHub Desktop.
Create a new Azure AD Change Notification Subscription for the 'User' ObjectClass and forward events to an Azure PowerShell Function. Associated Blogpost https://blog.darrenjrobinson.com/subscribing-to-azure-ad-change-notifications-with-powershell/
# Notifidcation Configuration
$expiryMaxLength = 3
$expiryHours = ($expiryMaxLength * 24) / 2
$clientStateValue = New-Guid
$notificationExpiry = (get-date).addHours($expiryHours).ToUniversalTime()
$utcExpiry = get-date $notificationExpiry -Format yyyy-MM-ddThh:mm:ss.0000000Z
# AAD User and Application Configuration
$graphAutomationClientID = "azureADApplicationClientID"
$graphAutomationSecret = "azureADApplicationSecret"
$graphAutomationTenantID = "azureADTenantID"
$graphAutomationUserUPN = "AzureADUser@yourTenant.onmicrosoft.com"
$graphAutomationUserPWD = "AzureADUserPassword"
# AuthN and get an Access Token
$delegatedToken = (Invoke-RestMethod -uri "https://login.microsoftonline.com/$($graphAutomationTenantID)/oauth2/token" `
-Method Post `
-Headers @{"Content-Type" = "application/x-www-form-urlencoded" } `
-Body "grant_type=password&resource=https://graph.microsoft.com&client_id=$($graphAutomationClientID)&username=$($graphAutomationUserUPN)&password=$($graphAutomationUserPWD)&client_secret=$($graphAutomationSecret)").access_token
# Azure AD Users change notification subscription configuration
$createSubscriptionBody = @{
changeType = "updated"
notificationUrl = "https://yourAzurePowerShellFunction.azurewebsites.net/api/receivechangenotification?code=Iy8bpuOO....yourAzureFunctionCode.....GQ%3D%3D"
clientState = $clientStateValue.Guid
resource = "/users"
expirationDateTime = "$($utcExpiry)"
latestSupportedTlsVersion = "v1_2"
}
# Create Notification Subscription
$newUsersNotificationSubscription = Invoke-RestMethod -method Post `
-Uri "https://graph.microsoft.com/v1.0/subscriptions" `
-body ($createSubscriptionBody | convertTo-json) `
-Headers @{Authorization = "Bearer $($delegatedToken)"; "content-type" = "application/json"}
$newUsersNotificationSubscription
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment