Azure Event Hub || Read events from Azure Event Hub using Storage SAS Token
Published Dec 19 2019 05:55 AM 3,187 Views

Use Case:

To read the events from Azure Event hub using Storage SAS Token.

 

Pre-Requisites:

  • Azure Event hub Namespace
  • Azure Storage Account SAS Token
  • Console Application to read the published

Steps to follow:

As a part of the working, Azure Event hub uses storage account while reading events to implement features like checkpointing under the Event Processor Host implementation. For this purpose, it is necessary to pass the storage connection string ,this article can be used in scenario where  in we do not want to expose the full storage connection  string and only want to authenticate using storage SAS token.

 

Ready made sample to read events out of event hub using connection string can be found here

 

To generate SAS token for the storage account, we can either use Azure Portal using the Shared Access Signature blade on storage account or use the below piece of code:

 

static string GetAccountSASToken()

{

    const string ConnectionString = "DefaultEndpointsProtocol=https;AccountName=<storage-account>;AccountKey=<account-key>";

    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionString);

    SharedAccessAccountPolicy policy = new SharedAccessAccountPolicy()

        {

            Permissions = SharedAccessAccountPermissions.Read | SharedAccessAccountPermissions.Write | SharedAccessAccountPermissions.List,

            Services = SharedAccessAccountServices.Blob | SharedAccessAccountServices.File,

            ResourceTypes = SharedAccessAccountResourceTypes.Service,

            SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),

            Protocols = SharedAccessProtocol.HttpsOnly

        };

    return storageAccount.GetSharedAccessSignature(policy);

}

To pass storage SAS token , we need to initialize the EventProcessorHost instance from the readymade code  in the below fashion:

 

var eventProcessorHost = new EventProcessorHost(new Uri(Uristring), EventHubName,

                PartitionReceiver.DefaultConsumerGroupName,

                TokenProvider.CreateSharedAccessSignatureTokenProvider( KeyName , KeyValue),

                new CloudStorageAccount(new StorageCredentials(StorageSasToken), StorageAccountName, null, true),

                StorageContainerName);

 

The format for the parameters is as below:

Uristring = "sb://{event hub namespace}.servicebus.windows.net"

KeyName = Event hub Policy name

KeyValue = Event hub key value

StorageSasToken =  Storage SAS token provided by Azure Portal or code.

StorageAccountName = Name of Storage account which would be used.

StorageContainerName = Name of Storage container to acquire lease on. 

 

Running the  receive console application, you should be able to read the events from event hub while using SAS token.

Hope this helps!

Version history
Last update:
‎Dec 19 2019 05:55 AM
Updated by: