| | 0

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

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:
    sepagoLabs-EventHub
  •  Event Hub name:
    workplaceclients
  •  Access policy name:
    ReceivePolicy
  •  Access Policy key:
    OmT7XZb5L3TdIWYblKZ5ReJ/xxxxxxxxxxxxxxxxxxxxxx=
  •  URI:
    sepagolabs-eventhub.servicebus.windows.net/workplaceclientsNote:
    The URI is build like this: <Name space>.servicebus.windows.net/<Event Hub name>

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
[Reflection.Assembly]::LoadWithPartialName("System.Web")| out-null
#Parameter
$URI="sepagolabs-eventhub.servicebus.windows.net/workplaceclients"
$Access_Policy_Name="ReceivePolicy"
$Access_Policy_Key="OmT7XZb5L3TdIWYblKZ5ReJ/xxxxxxxxxxxxxxxxxxxxxxx="
#Token expires now+300
$Expires=([DateTimeOffset]::Now.ToUnixTimeSeconds())+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
$SASToken

 

The output will look like this:

1
SharedAccessSignature sr=sepagolabseventhub.servicebus.windows.net%2fworkplaceclients&sig=dCFmFxxxxxxxxqspa9LpuSHFqyxxPQ%2fxxxxxxxxxxxxLk%3d&se=14500000037&skn=ReceivePolicy

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

https://<URI>/messages?timeout=60&api-version=2014-01

in my case:

https://sepagolabs-eventhub.servicebus.windows.net/workplaceclients/messages?timeout=60&api-version=2014-01

with the following headers:

Authorization: SharedAccessSignature sr=sepagolabseventhub.servicebus.windows.net%2fworkplaceclients&sig=dCFmFxxxxxxxxqspa9LpuSHFqyxxPQ%2fxxxxxxxxxxxxLk%3d&se=14500000037&skn=ReceivePolicy

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

For example, with Fiddler:

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