Create an Event Grid and access it via a Web App with a common User Managed Identity. An Azure scenario explained.

In this article, we’ll walk through the steps to create a User Managed Identity, and use it to authenticate between Azure Resources, create events from an .NET Azure App Service and push them into an Event Grid topic. All this will be done using only Azure CLI commands. But first of all lets see why a Managed Identity should be used in the first place.

What are Managed Identities?

Managed identities are a feature of Azure Entra ID (previously called Azure Active Directory) that provides Azure services with an automatically managed identity. This identity can be used to authenticate to any service that supports Azure AD authentication, without needing to manage credentials.

The benefits of Managed Identities are:

Step 1: Create a new User Managed Identity

First, create a resource group where all your resources will be organized. The values of the properties (name, location, etc.) in the shell commands in this article can be changed based on your preference:

az group create --name TestManagedIdentityResourceGroup --location switzerlandnorth

Next, create a User Managed Identity within the resource group you just created:

az identity create --resource-group TestManagedIdentityResourceGroup --name TestManagedIdentity

Step 2: Create a new Event Grid Topic

Now, create an Event Grid Topic in the same resource group:

az eventgrid topic create \
  --resource-group TestManagedIdentityResourceGroup \
  --name TestEventGridTopicWithManagedIdentity \
  --location switzerlandnorth

Step 3: Assign a new role to the Managed Identity

You want your Managed Identity to be able to write and get events from the Event Grid. For that, you will have to assign the “EventGrid Data Contributor” role.

az role assignment create \
  --assignee 00000000-0000-0000-0000-000000000000 \
  --role "EventGrid Data Contributor" \
  --scope "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/TestManagedIdentityResourceGroup/providers/Microsoft.EventGrid/topics/TestEventGridTopicWithManagedIdentity"

Step 4: Create a new Web App

First you will create a new App Service Plan which uses the free pricing tier:

az appservice plan create \
  --name TestManagedIdentityAppServicePlan \
  --resource-group TestManagedIdentityResourceGroup \
  --sku F1

Now, create a new .NET Web App:

az webapp create \
  --resource-group TestManagedIdentityResourceGroup \
  --plan TestManagedIdentityAppServicePlan \
  --name TestManagedIdentityWebApp \
  --runtime "DOTNETCORE:8.0"

Step 5: Assign the Managed Identity to the Web App

In order the Web App to be able to publish events into the Event Grid, we have to assign the User Managed Identity to the Web App. Use the following Azure CLI command:

az webapp identity assign \
  --resource-group TestManagedIdentityResourceGroup \
  --name TestManagedIdentityWebApp \
  --identities /subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/TestManagedIdentityResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/TestManagedIdentity

Step 6: Create a new .NET WebAPI application

The orchestration of the Azure Resources is completed. Now, you will need to create a small WebAPI to push events to the Event Grid. This WebAPI will use the User Managed Identity to authenticate and send events. Below is the code for the Controller, which was modified from the default WeatherForecastController when we instantiated a new .NET WebAPI app:

using Azure.Messaging.EventGrid;
using Azure.Identity;
using Microsoft.AspNetCore.Mvc;

namespace ManagedIdentityWithAppServiceAndStorageAccount.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpPost(Name = "PostWeatherTemperature")]
        public WeatherTemperature Post(int temperature, string city)
        {
            var credential = new DefaultAzureCredential(
                new DefaultAzureCredentialOptions
                {
                    ManagedIdentityClientId = "00000000-0000-0000-0000-000000000000"
                });

           var client = new EventGridPublisherClient(
               new Uri("https://testeventgridtopicwithmanagedidentity.switzerlandnorth-1.eventgrid.azure.net/api/events"), 
               credential);

            WeatherTemperature weatherTemperature = new()
            {
                Date = DateTime.UtcNow,
                TemperatureC = temperature,
                City = city
            };

            var events = new List<EventGridEvent>
            {
                new(
                    subject: "WeatherForecast event",
                    eventType: "WeatherForecast.Temperature",
                    dataVersion: "1.0",
                    data: weatherTemperature)
            };

            client.SendEvents(events);

            return weatherTemperature;
        }
    }
}

You can now publish this app into the Azure Web App and use Postman to make some POST requests to the API. The authentication works, and the events are getting written into the Event Grid Topic.

Delete the resource group

If you are not going to use the resource group and all its associated services anymore, you can delete them with the following command:

az group delete --name TestManagedIdentityResourceGroup --no-wait --yes -y 

This will delete not only the resource group but also the Web App, the Event Grid, and the User Managed Identity.

Conclusion

This guide has described all the necessary steps for creating a new User Managed Identity and using it in an everyday scenario of Azure Resources. Managed Identities provide a secure and easy way to manage credentials, enhancing both security and ease of use. Feel free to add a comment for any questions or suggestions you have.

comments powered by Disqus