Skip to content

Instantly share code, notes, and snippets.

@guss77
Last active April 19, 2021 22:05
Show Gist options
  • Save guss77/2a1d0b67d1fca74104f9ce970d2f64d1 to your computer and use it in GitHub Desktop.
Save guss77/2a1d0b67d1fca74104f9ce970d2f64d1 to your computer and use it in GitHub Desktop.
Create a shared key for Azure storage REST API
#!/bin/bash
# Based on https://docs.microsoft.com/en-us/azure/storage/common/storage-rest-api-auth
function GetCanonicalizedResource() {
local address="$1" storageAccountName="$2"
echo -n "/${storageAccountName}$(cut -d? -f1 <<<"$address")"
cut -d? -f2- <<<"$address" | tr '&' '\n' | (while IFS="=" read key val; do printf '\n%s:%s' "$key" "$val"; done)
}
function GetAuthorizationHeader() {
# ported from https://github.com/Azure-Samples/storage-dotnet-rest-api-with-auth/blob/master/StorageRestApiAuth/AzureStorageAuthenticationHelper.cs
local storageAccountName="$1" storageAccountKey="$2" method="$3" address="$4"
# method, body content-length, md5, ifmatch, x-ms- headers list, canonical resource
SignatureBytes="$(printf "%s\n\n\n%s\n%s\n\n\n\n%s\n\n\n\n%s%s" \
"$method" "" "" "" "" "$(GetCanonicalizedResource "${address}" "${storageAccountName}")")"
signature=$(openssl dgst -sha256 -hmac \
"$(base64 -d <<<"${storageAccountKey}")" -binary <<<"$SignatureBytes" | base64)
echo "SharedKey ${storageAccountName}:${signature}"
}
# this example tries to authorize a call to show storage queue metadata
storageAccountKey="$(az storage account keys list \
--resource-group $(get_rgroup_name) --account-name $(get_az_storage_account) | jq -r '.[0].value')"
sharedKey="$(GetAuthorizationHeader "$(get_az_storage_account)" "$storageAccountKey" \
GET "/jobs-azure-dev?comp=metadata")"
curl -H "Authorization: $sharedKey" $(get_queue_url)?comp=metadata
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment