Validating an HTTP Endpoint to Receive Events from Azure Event Grid

Introduction

This article explains how to verify an HTTP endpoint before receiving and deserializing events from an event subscription.

Prerequisites

To validate an HTTP endpoint to receive events from Azure Event Grid, you'll indeed need to create an Azure Function App with an HTTP-triggered function.

Endpoint Validation

You want to take care of Microsoft.EventGrid.SubscriptionValidationEvent related to subscription validation. Event Grid sends a validation event to the endpoint with a validation code in the data payload each time an event is subscribed to. To verify that the endpoint is justified and yours, it must amplify this back in the body of the response. To deserialize a Binary Data instance containing one or more events into an array of EventGridEvent, use the ParseMany() method. You could use the Parse method in place of deserializing a single event if you were aware in advance.

Use the following code to programmatically amplify the validation code.

/// <summary>
/// EventIntake Function.
/// </summary>
/// <param name="req">The Req.</param>
/// <param name="log">The Log.</param>
/// <returns>Returns Response Code.</returns>
[FunctionName("EventGridFunction")]
public async Task<IActionResult> EventIntake(
	[HttpTrigger(AuthorizationLevel.User, "post", Route = null)]
HttpRequest req, ILogger log)
{
	try
	{
		BinaryData events = await BinaryData.FromStreamAsync(req.Body);
		log.LogInformation($"Received events: {events}");
		EventGridEvent[] eventGridEvents = EventGridEvent.ParseMany(events);
		var validationEvent = eventGridEvents.FirstOrDefault(x => x.EventType == "Microsoft.EventGrid.SubscriptionValidationEvent");
		if (validationEvent != null)
		{
			var validationData = validationEvent.Data.ToObjectFromJson<SubscriptionValidationEventData>();
			var validationResponse = new
			{
				ValidationResponse = validationData.ValidationCode
			};

			log.LogInformation("Received Validate Subscription event. Echo back the validation code {code}", validationResponse.ValidationResponse);
			return new OkObjectResult(validationResponse);
		}

		// Your Logic

		return new OkObjectResult(string.Empty);
	}
	catch (Exception e)
	{
		log.LogError(e, "Unable to pass event grid message");
		return new BadRequestObjectResult(e);
	}
}

Test Validation Response

Copy and paste the sample event into the function's test field to test the validation response function.

[{
  "id": "21915976-38b1-449d-8edf-a406ee6d23e5",
  "topic": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "subject": "",
  "data": {
    "validationCode": "6179467e-fefb-43c3-b92f-67370daedf99"
  },
  "eventType": "Microsoft.EventGrid.SubscriptionValidationEvent",
  "eventTime": "2018-01-25T22:12:19.4556811Z",
  "metadataVersion": "1",
  "dataVersion": "1"
}]

Authorization

Conclusion

By following the guidelines presented in this article, you can effectively verify HTTP endpoints before receiving and deserializing events from event subscriptions, enhancing the security and reliability of your event-driven architecture in Azure Event Grid.