Last active
June 1, 2021 21:07
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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