I want to create a webhook to get notified when a user is created or updated on the Azure active directory. My goal is to trigger a function app using the webhook.
Is there a separate Graph API to get those details?
Create a subscription in Graph API which will monitor users for creation and updating.
Follow the below steps to trigger the function when new user is created or updated.
Create a App Registration
Users.ReadWrite.All
for Delegate and Application.Create a Function App and deploy a HTTP trigger function
I have created a .NET 8 Http Trigger function.
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;
namespace FunctionApp13
{
public class Function1
{
private readonly ILogger<Function1> _logger;
public Function1(ILogger<Function1> logger)
{
_logger = logger;
}
[Function("Function1")]
public async Task<IActionResult> RunAsync(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequest req)
{
_logger.LogInformation("Webhook triggered.");
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
if (req.Query.ContainsKey("validationToken"))
{
string validationToken = req.Query["validationToken"];
_logger.LogInformation($"Validation token received: {validationToken}");
return new ContentResult()
{
Content = validationToken,
ContentType = "text/plain",
StatusCode = StatusCodes.Status200OK
};
}
var data = JsonSerializer.Deserialize<WebhookNotification>(requestBody);
_logger.LogInformation($"Notification received: {data.value}");
string expectedClientState = "state_secret";
if (data?.value[0]?.clientState != expectedClientState)
{
_logger.LogWarning("Client state mismatch.");
return new UnauthorizedResult();
}
return new OkResult();
}
}
public class WebhookNotification
{
public List<UserEventData> value { get; set; }
}
public class UserEventData
{
public string clientState { get; set; }
}
}
Program.cs
:
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
var host = new HostBuilder()
.ConfigureFunctionsWebApplication()
.ConfigureServices(services =>
{
services.AddApplicationInsightsTelemetryWorkerService();
services.ConfigureFunctionsApplicationInsights();
services.Configure<LoggerFilterOptions>(option => option.Rules.Clear());
})
.Build();
host.Run();
Deploy it to function and get the URL.
Create Subscription in Graph API
I am using Postman here to create subscription.
https://graph.microsoft.com/v1.0/subscriptions
with raw body in json data{
"changeType": "created,updated",
"notificationUrl": "https://graphfunc6june.azurewebsites.net/api/Function1", #your function http trigger url
"resource": "/users",
"expirationDateTime": "2024-06-08T05:00:00Z",
"clientState": "state_secret"
}
OUTPUT
: