使用 Azure Active Directory 对托管标识的事件中心资源访问进行身份验证Authenticate a managed identity with Azure Active Directory to access Event Hubs Resources

Azure 事件中心支持使用 Azure 资源的托管标识进行 Azure Active Directory (Azure AD) 身份验证。Azure Event Hubs supports Azure Active Directory (Azure AD) authentication with managed identities for Azure resources. Azure 资源的托管标识可以从 Azure 虚拟机 (VM)、函数应用、虚拟机规模集和其他服务中运行的应用程序使用 Azure AD 凭据授权对事件中心资源的访问权限。Managed identities for Azure resources can authorize access to Event Hubs resources using Azure AD credentials from applications running in Azure Virtual Machines (VMs), Function apps, Virtual Machine Scale Sets, and other services. 将 Azure 资源的托管标识与 Azure AD 身份验证结合使用,可避免将凭据随在云中运行的应用程序一起存储。By using managed identities for Azure resources together with Azure AD authentication, you can avoid storing credentials with your applications that run in the cloud.

本文介绍如何在 Azure VM 中使用托管标识授予对事件中心的访问权限。This article shows how to authorize access to an event hub by using a managed identity from an Azure VM.

在 VM 上启用托管标识Enable managed identities on a VM

在使用 Azure 资源的托管标识对 VM 中的事件中心资源授权之前,必须首先在 VM 上启用 Azure 资源的托管标识。Before you can use managed identities for Azure Resources to authorize Event Hubs resources from your VM, you must first enable managed identities for Azure Resources on the VM. 若要了解如何为 Azure 资源启用托管标识,请参阅下述文章之一:To learn how to enable managed identities for Azure Resources, see one of these articles:

向 Azure AD 中的托管标识授予权限Grant permissions to a managed identity in Azure AD

若要通过应用程序中的托管标识授权对事件中心服务的请求,请先为该托管标识配置基于角色的访问控制 (RBAC) 设置。To authorize a request to Event Hubs service from a managed identity in your application, first configure role-based access control (RBAC) settings for that managed identity. Azure 事件中心定义 Azure 角色,这些角色涵盖了从事件中心进行发送和读取操作所需的权限。Azure Event Hubs defines Azure roles that encompass permissions for sending and reading from Event Hubs. 将 Azure 角色分配到某个托管标识后,将在适当的范围授予该托管标识访问事件中心数据的权限。When the Azure role is assigned to a managed identity, the managed identity is granted access to Event Hubs data at the appropriate scope.

有关如何分配 Azure 角色的详细信息,请参阅使用 Azure Active Directory 进行身份验证,以便访问事件中心资源For more information about assigning Azure roles, see Authenticate with Azure Active Directory for access to Event Hubs resources.

将事件中心与托管标识结合使用Use Event Hubs with managed identities

若要将事件中心与托管标识配合使用,需为标识分配角色和相应的范围。To use Event Hubs with managed identities, you need to assign the identity the role and the appropriate scope. 此部分的过程使用一个简单的应用程序,该应用程序在托管标识下运行并访问事件中心资源。The procedure in this section uses a simple application that runs under a managed identity and accesses Event Hubs resources.

在这里,我们将使用一个在 Azure 应用服务中托管的示例 Web 应用程序。Here we're using a sample web application hosted in Azure App Service. 有关如何创建 Web 应用程序的分步说明,请参阅在 Azure 中创建 ASP.NET Core Web 应用For step-by-step instructions for creating a web application, see Create an ASP.NET Core web app in Azure

创建应用程序后,请执行以下步骤:Once the application is created, follow these steps:

  1. 转到“设置”,然后选择“标识”。Go to Settings and select Identity.

  2. 选择“状态”,将其切换到“启用”。Select the Status to be On.

  3. 选择“保存”,保存设置。Select Save to save the setting.

    Web 应用的托管标识

启用此设置后,会在 Azure Active Directory (Azure AD) 中创建一个新的服务标识并将其配置到应用服务主机中。Once you've enabled this setting, a new service identity is created in your Azure Active Directory (Azure AD) and configured into the App Service host.

现在,请将此服务标识分配给事件中心资源中所需范围中的某个角色。Now, assign this service identity to a role in the required scope in your Event Hubs resources.

使用 Azure 门户分配 Azure 角色To Assign Azure roles using the Azure portal

若要为事件中心资源分配角色,请导航到 Azure 门户中的该资源。To assign a role to Event Hubs resources, navigate to that resource in the Azure portal. 显示资源的“访问控制(标识和访问管理)”设置,并按以下说明管理角色分配:Display the Access Control (IAM) settings for the resource, and follow these instructions to manage role assignments:

备注

以下步骤为事件中心命名空间分配服务标识角色。The following steps assigns a service identity role to your Event Hubs namespaces. 可以遵循相同的步骤来分配限定为事件中心资源范围的角色。You can follow the same steps to assign a role scoped to any Event Hubs resource.

  1. 在 Azure 门户中导航到事件中心命名空间,显示该命名空间的“概览”。In the Azure portal, navigate to your Event Hubs namespace and display the Overview for the namespace.

  2. 选择左侧菜单上的“访问控制(标识和访问管理)”,显示事件中心的访问控制设置。Select Access Control (IAM) on the left menu to display access control settings for the event hub.

  3. 选择“角色分配”选项卡以查看角色分配列表。Select the Role assignments tab to see the list of role assignments.

  4. 选择“添加”以添加新角色。Select Add to add a new role.

  5. 在“添加角色分配”页上,选择要分配的事件中心角色。On the Add role assignment page, select the Event Hubs roles that you want to assign. 然后通过搜索找到已注册的服务标识,以便分配该角色。Then search to locate the service identity you had registered to assign the role.

    “添加角色分配”页

  6. 选择“保存” 。Select Save. 分配有该角色的标识列出在该角色下。The identity to whom you assigned the role appears listed under that role. 例如,下图显示服务标识有事件中心数据所有者。For example, the following image shows that service identity has Event Hubs Data owner.

    分配给角色的标识

分配此角色后,Web 应用程序即可访问已定义范围内的事件中心资源。Once you've assigned the role, the web application will have access to the Event Hubs resources under the defined scope.

测试 Web 应用程序Test the web application

  1. 创建事件中心命名空间和事件中心。Create an Event Hubs namespace and an event hub.
  2. 将 Web 应用部署到 Azure。Deploy the web app to Azure. 请参阅下面的选项卡式部分,获取 GitHub 上的 Web 应用程序的链接。See the following tabbed section for links to the web application on GitHub.
  3. 确保将 SendReceive.aspx 设置为 Web 应用的默认文档。Ensure that the SendReceive.aspx is set as the default document for the web app.
  4. 为 Web 应用启用标识Enable identity for the web app.
  5. 将此标识分配给命名空间级别或事件中心级别的“事件中心数据所有者”角色。Assign this identity to the Event Hubs Data Owner role at the namespace level or event hub level.
  6. 运行 Web 应用程序,输入命名空间名称和事件中心名称,输入一条消息,然后选择“发送”。Run the web application, enter the namespace name and event hub name, a message, and select Send. 若要接收事件,请选择“接收”。To receive the event, select Receive.

现在可以启动 Web 应用程序并将浏览器指向示例 aspx 页面了。You can now launch you web application and point your browser to the sample aspx page. 可以在 GitHub 存储库中找到用于通过事件中心资源发送和接收数据的示例 Web 应用程序。You can find the sample web application that sends and receives data from Event Hubs resources in the GitHub repo.

安装 NuGet 中的最新包,开始使用 EventHubProducerClient 向事件中心发送事件,使用 EventHubConsumerClient 接收事件。Install the latest package from NuGet, and start sending events to Event Hubs using EventHubProducerClient and receiving events using EventHubConsumerClient.

备注

有关使用托管标识将事件发布到事件中心的 Java 示例,请参阅在 GitHub 上使用 Azure 标识示例发布事件For a Java sample that uses a managed identity to publish events to an event hub, see Publish events with Azure identity sample on GitHub.

protected async void btnSend_Click(object sender, EventArgs e)
{
    await using (EventHubProducerClient producerClient = new EventHubProducerClient(txtNamespace.Text, txtEventHub.Text, new DefaultAzureCredential()))
    {
        // create a batch
        using (EventDataBatch eventBatch = await producerClient.CreateBatchAsync())
        {

            // add events to the batch. only one in this case. 
            eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes(txtData.Text)));

            // send the batch to the event hub
            await producerClient.SendAsync(eventBatch);
        }

        txtOutput.Text = $"{DateTime.Now} - SENT{Environment.NewLine}{txtOutput.Text}";
    }
}
protected async void btnReceive_Click(object sender, EventArgs e)
{
    await using (var consumerClient = new EventHubConsumerClient(EventHubConsumerClient.DefaultConsumerGroupName, $"{txtNamespace.Text}.servicebus.chinacloudapi.cn", txtEventHub.Text, new DefaultAzureCredential()))
    {
        int eventsRead = 0;
        try
        {
            using CancellationTokenSource cancellationSource = new CancellationTokenSource();
            cancellationSource.CancelAfter(TimeSpan.FromSeconds(5));

            await foreach (PartitionEvent partitionEvent in consumerClient.ReadEventsAsync(cancellationSource.Token))
            {
                txtOutput.Text = $"Event Read: { Encoding.UTF8.GetString(partitionEvent.Data.Body.ToArray()) }{ Environment.NewLine}" + txtOutput.Text;
                eventsRead++;
            }
        }
        catch (TaskCanceledException ex)
        {
            txtOutput.Text = $"Number of events read: {eventsRead}{ Environment.NewLine}" + txtOutput.Text;
        }
    }
}

用于 Kafka 的事件中心Event Hubs for Kafka

可以使用 Apache Kafka 应用程序通过托管标识 OAuth 向 Azure 事件中心发送消息,以及从 Azure 事件中心接收消息。You can use Apache Kafka applications to send messages to and receive messages from Azure Event Hubs using managed identity OAuth. 窗口 GitHub 上的以下示例:用于 Kafka 的事件中心 - 使用托管标识 OAuth 发送和接收消息See the following sample on GitHub: Event Hubs for Kafka - send and receive messages using managed identity OAuth.

示例Samples

后续步骤Next steps