I’ve always kept around a handy console application that would generate SAS tokens for a Service Bus queue or topic. While it was convenient, it also seemed a little silly to have to keep that application around for such a trivial task.
Generating SAS tokens from Bash
While researching for alternatives, I came across this helpful sample of how to generate a SAS token for Event Hubs from Bash: https://docs.microsoft.com/en-us/rest/api/eventhub/generate-sas-token#bash.
I thought it would be cool to see if the same thing could be done for a Service Bus queue – this time from the Azure Cloud Shell.
Requirements
To execute the script later in this post, all you’ll need is:
- A Service Bus namespace
- A queue or topic that you want to generate a token for
- A shared access policy (please don’t use the root) to limit access to the entity
For more about shared access authorization policies, please read: https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-sas#shared-access-authorization-policies.
Cloud Shell
Both OpenSSL and jp are already installed on the Azure Cloud Shell. Just one of a bazillion reasons to love this utility!
Based off of the Event Hub sample, the script for Service Bus is almost the same:
rgname={your-resource-group-name} servicebus_uri={namespace-name}.servicebus.windows.net/{queue-name} shared_access_key_name={your-shared-access-key-name} shared_access_key={your-shared-access-key} EXPIRY=${EXPIRY:=$((60 * 60 * 24))} ENCODED_URI=$(echo -n $servicebus_uri | jq -s -R -r @uri) TTL=$(($(date +%s) + $EXPIRY)) UTF8_SIGNATURE=$(printf "%s\n%s" $ENCODED_URI $TTL | iconv -t utf8) HASH=$(echo -n "$UTF8_SIGNATURE" | openssl sha256 -hmac $shared_access_key -binary | base64) ENCODED_HASH=$(echo -n $HASH | jq -s -R -r @uri) echo -n "SharedAccessSignature sr=$ENCODED_URI&sig=$ENCODED_HASH&se=$TTL&skn=$shared_access_key_name"
Gist link: https://gist.github.com/dbarkol/d62be281331f8c92aa1ca00275486c96
I can now get rid of that console application and get the same results from the cloud shell – anywhere, anytime!
David, you’re a lifesaver! Still works like a charm!