How to generate a SAS-Token to access Microsoft Azure Event Hub (PowerShell, AzureEventHub, Azure)

Marcel Meurer's picture

For an upcoming project I will send short data telegrams to an Event Hub on Microsoft Azure. I have some experience with calling different services on Azure via API (e.g. Azure Machine Learning). But the authorization to an Azure ML Web Service and to an Event Hub is very different. Azure ML only requires an Authorization BEARER. Event Hub needs a SAS-Token. It took some time to find out how to generate a correct authorization string.

Here I will explain in short how to generate a valid SAS for an Event Hub:

Go to your Event Hub: Service Bus -> “Name Space” -> All -> “name” -> Configure

The Event Hub is already created:

  • Name space:

  • Event Hub name:

  • Access policy name:

  • Access Policy key:

  • URI:

    The URI is build like this: <Name space><Event Hub name>

To build the SAS-Token use a short PowerShell Script:

[Reflection.Assembly]::LoadWithPartialName("System.Web")| out-null





#Token expires now+300


#Building Token

$SignatureString=[System.Web.HttpUtility]::UrlEncode($URI)+ "`n" + [string]$Expires

$HMAC = New-Object System.Security.Cryptography.HMACSHA256

$HMAC.key = [Text.Encoding]::ASCII.GetBytes($Access_Policy_Key)

$Signature = $HMAC.ComputeHash([Text.Encoding]::ASCII.GetBytes($SignatureString))

$Signature = [Convert]::ToBase64String($Signature)

$SASToken = "SharedAccessSignature sr=" + [System.Web.HttpUtility]::UrlEncode($URI) + "&sig=" + [System.Web.HttpUtility]::UrlEncode($Signature) + "&se=" + $Expires + "&skn=" + $Access_Policy_Name



The output will look like this:


To test access to the Event Hub, make a http-post to:


in my case:

with the following headers:

Authorization: SharedAccessSignature

Content-Type: application/atom+xml;type=entry;charset=utf-8

For example, with Fiddler:

At the dashboard, valid and invalid accesses will be displayed:

Shared access policies
is there a way to create the Shared access policies from powershell or does that have to be through the portal?
Add new comment
By submitting this form, you accept the Mollom privacy policy.