How to automate creation of Microsoft Graph API notifications through Azure Event Grid and Partner Topic

Receive Microsoft Graph API change events through Azure Event Grid

In one of the previous article, I showed how to manually create a Partner Topic in Azure Event Grid to receive notifications from the Microsoft Graph API.

In this article, I will focus on how to automate the creation of Microsoft Graph API notifications through Azure Event Grid and Partner Topic using Bicep and the Microsoft Graph PowerShell SDK.

Prerequisites

  • The Az PowerShell module
  • Bicep to automate the creation of all Azure resources
  • The Microsoft Graph API PowerShell SDK to create the subscription

I will use Visual Studio Code to write the Bicep code and PowerShell scripts. The ms-azuretools.vscode-bicep extension brings Bicep language support for Visual Studio Code.

The Az PowerShell module is used to execute the Bicep code and the Microsoft Graph PowerShell SDK to create the subscription.

Steps

The steps will be:

  1. Create Azure Resource Group
  2. Create Event Grid Partner Configuration and authorize the Microsoft Graph API Partner
  3. Create Graph subscription for Event Grid
  4. Enable Event Grid Partner Topic

Let's start with the Bicep file to create the Event Grid Partner Configuration and authorize the Microsoft Graph API partner.

eventgrid.bicep:

param baseTime string = utcNow('u')

var authorizationExpirationTimeInUtc = dateTimeAdd(baseTime, 'P1Y')

resource eventGridPartnerConfiguration 'Microsoft.EventGrid/partnerConfigurations@2025-02-15' = {
  location: 'global'
  name: 'default'
  properties: {
    partnerAuthorization: {
      defaultMaximumExpirationTimeInDays: 365
      authorizedPartnersList: [
        {
          partnerName: 'MicrosoftGraphAPI'
          partnerRegistrationImmutableId: 'c02e0126-707c-436d-b6a1-175d2748fb58'
          authorizationExpirationTimeInUtc: authorizationExpirationTimeInUtc
        }
      ]
    }
  }
}

The location must be set to global. The partner name is MicrosoftGraphAPI with the id c02e0126-707c-436d-b6a1-175d2748fb58. The authorizationExpirationTimeInUtc is set to one year from the current time.

Now, create the main Bicep file and Bicep parameters file.

main.bicep:

targetScope = 'subscription'

param resourceGroupLocation string
param resourceGroupName string

resource newResourceGroup 'Microsoft.Resources/resourceGroups@2024-03-01' = {
  location: resourceGroupLocation
  name: resourceGroupName
}

module eventgrid 'eventgrid.bicep' = {
  name: 'eventgrid'
  scope: newResourceGroup
}

output resourceGroupName string = resourceGroupName

main.bicepparam:

using 'main.bicep'

param resourceGroupLocation = 'germanywestcentral'
param resourceGroupName = 'graphapi-notifications'

The Bicep parameters file contains the location of the resource group and its name. The Bicep file creates a new resource group and deploys the eventgrid.bicep module to it.

No more Bicep code is needed.

The next step is to execute the Bicep code. I will use the Az PowerShell module to deploy the Bicep code.

# deploy a Bicep template to create a resource group and set up a Microsoft Graph subscription with Event Grid notifications
$tenantId = '<tenant_id>'
Connect-AzAccount -Tenant $tenantId

$deployment = New-AzSubscriptionDeployment -TemplateFile main.bicep -TemplateParameterFile main.bicepparam -Location 'East US'
$resourceGroupName = $deployment.outputs.resourceGroupName.value

Write-Host "Resource Group Name: $resourceGroupName"

# Create a Microsoft Graph subscription for user changes
Import-Module Microsoft.Graph.ChangeNotifications

$azureSubscriptionId = '<azure_subscription_id>'
$partnerTopic = 'users'
$location = 'eastus'
$appId = '<client_id>'
$clientSecret = '<client_secret>'
$clientSecretCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $appId, (ConvertTo-SecureString -String $clientSecret -AsPlainText -Force)

Connect-MgGraph -TenantId $tenantId -ClientSecretCredential $clientSecretCredential

$params = @{
    changeType = "Updated,Deleted,Created"
    notificationUrl = "EventGrid:?azuresubscriptionid=$azureSubscriptionId&resourcegroup=$resourceGroupName&partnertopic=$partnerTopic&location=$location"
    lifecycleNotificationUrl = "EventGrid:?azuresubscriptionid=$azureSubscriptionId&resourcegroup=$resourceGroupName&partnertopic=$partnerTopic&location=$location"
    expirationDateTime = [System.DateTime]::Parse("2025-06-06T18:23:45.9356913Z")
    resource = "users"
    latestSupportedTlsVersion = "v1_2"
}

$graphSubscription = New-MgSubscription -BodyParameter $params

Write-Host "Graph Subscription ID: $($graphSubscription.Id)"

# Enable the Event Grid Partner Topic
Enable-AzEventGridPartnerTopic -Name $partnerTopic -ResourceGroupName $resourceGroupName

The Connect-AzAccount cmdlet connects to the Azure with prompting to select the account.

The New-AzSubscriptionDeployment cmdlet deploys the Bicep code to create the resource group and Event Grid Partner Configuration.

The output of the deployment contains the resource group name, which is used in notificationUrl and lifecycleNotificationUrl parameters for the Microsoft Graph subscription.

The New-MgSubscription cmdlet creates the Microsoft Graph subscription for user changes. The notificationUrl and lifecycleNotificationUrl parameters are set to the Event Grid Partner Topic URL, which includes the Azure subscription ID, resource group name, partner topic name, and location.

You can login to the Microsoft Graph either on behalf of a user or using the client secret of the Entra ID application. In this example, I use the Connect-MgGraph cmdlet with the client secret credential. The Entra ID app has granted the application permission User.Read.All to be able to create the subscription for user changes.

Finally, the Enable-AzEventGridPartnerTopic cmdlet enables the Event Grid Partner Topic.

If you run the PowerShell script:

PS C:\Work\EventGridGraph> ./main.ps1

you can check the result in the Azure Portal:

Use for example the Graph Explorer to check that the subscription is created:

Conclusion

Using Bicep and the Microsoft Graph PowerShell SDK, you can easily automate the creation of Microsoft Graph API notifications through Azure Event Grid and Partner Topic.

Next time, I will show how to use Bicep to create Event Subscription for the Partner Topic to handle specific events from the Microsoft Graph API.

0
Buy Me a Coffee at ko-fi.com
An error has occurred. This application may no longer respond until reloaded. Reload x