zoukankan      html  css  js  c++  java
  • Azure Event Hub (2) 使用Azure AD授权访问Event Hub

      《Windows Azure Platform 系列文章目录

      Azure Event Hub事件中心支持两种授权方式:

    1. Azure Active Directory
    2. Shared access signatures (SAS,共享访问签名)

      针对第二种SAS的授权方式,Azure Portal上直接可以查看到具体的连接字符串,相对比较简单。

      本文主要介绍第一种,使用Azure AD授权访问Event Hub。

      在使用Azure AD授权之前,我们需要创建应用注册(App Registration),并获得tenant id, app id和app secret。

      具体可以参考:Windows Azure AD (7) 创建配置应用程序和服务主体 (Application and Service Principal)

      1.假设我们已经成功创建了一个应用注册(App Registration),如下图:

      

      2.我们需要在RBAC上,设置这个应用注册的权限。

      Azure 事件中心数据所有者,使用此角色可以授予对事件中心资源的完全访问权限。

      Azure 事件中心数据发送者,使用此角色可以授予对事件中心资源的发送访问权限。

      Azure 事件中心数据接收者,使用此角色可以授予对事件中心资源的使用/接收访问权限。

      

     

      3.我们这里演示的内容,是通过AAD给Event Hub发送消息

      4.我们打开Visual Studio,创建的项目类型为.Net Core。如下图:

      

     

      5.设置项目名称为EventHubSender。步骤略。

      6.在Program.cs中,增加引用

    using System;
    using System.Text;
    using System.Threading.Tasks;
    using Azure.Core;
    using Azure.Messaging.EventHubs;
    using Azure.Messaging.EventHubs.Producer;
    using Azure.Identity;

      7.在Nuget包管理中,增加以下package

      

      8.在Class Program中,增加如下代码:

    static EventHubProducerClient producerClient;
    //这里设置TenantID
    static readonly string TenantId = "";
    
    //这里设置ClientID
    static readonly string ClientId = "";
    
    //这里设置Client Secret
    static readonly string ClientSecret = "";
    
    //这里设置Event Hub命名空间
    static readonly string EventHubNamespace = "leieventhub01.servicebus.chinacloudapi.cn";
    
    //这里设置Event Hub Name
    static readonly string EventHubName = "event01";
    static async Task Main()
    {
                await ClientCredentialsScenarioAsync();
     }
    
    
     static async Task ClientCredentialsScenarioAsync()
            {
    var options = new ClientCertificateCredentialOptions { AuthorityHost = AzureAuthorityHosts.AzureChina }; TokenCredential credential = new ClientSecretCredential(TenantId, ClientId, ClientSecret, options); // Create a producer client that you can use to send events to an event hub producerClient = new EventHubProducerClient(EventHubNamespace, EventHubName, credential); // Create a batch of events EventDataBatch eventBatch; for (int i = 1; i <= numOfEvents; i++) { eventBatch = await producerClient.CreateBatchAsync(); eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes($"Event {i}"))); await producerClient.SendAsync(eventBatch); Console.WriteLine($"A Message {i} has been sent"); } }

       

  • 相关阅读:
    如何在EXCEL SHEET中 动态添加控件
    和菜鸟一起学OK6410之ADC模块
    和菜鸟一起学证券投资之消费物价指数CPI
    和菜鸟一起学证券投资之股市常见概念公式2
    作为软件工程师,你必须知道的20个常识
    和菜鸟一起学c++之虚函数
    和菜鸟一起学单片机之入门级led流水灯
    在国内各大软件下载网站上,“万能数据库查询分析器”已更新至 2.02 版本
    和菜鸟一起学证券投资之股市简单财务分析
    和菜鸟一起学OK6410之蜂鸣器buzzer字符驱动
  • 原文地址:https://www.cnblogs.com/threestone/p/15329693.html
Copyright © 2011-2022 走看看