Generate a Service Bus SAS Token from the Azure Cloud Shell

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:


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.


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:

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:



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:


I can now get rid of that console application and get the same results from the cloud shell – anywhere, anytime!


  1. David, you’re a lifesaver! Still works like a charm!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s