Generating Azure Storage Tokens On the Fly With PowerShell

As I talked about in last week’s blog post, it’s important to ensure that files that you store in blob are secure from public eyes. But how do you allow your automation to access them when needed? That’s where a Shared Access Signature (SAS) token comes into play.

A SAS token is essentially an authorized URI that grants the person or object using it rights to access the object that you are otherwise concealing from the world. You can specify the amount of time that the URI is valid for; the protocol that is allowed; and the specific permissions to the object (read, write, delete). Once the time has elapsed, the URI is no longer valid and the object is not accessible.

Let me show you how this works!

After we’ve logged into Azure and set the appropriate subscription context, We need to get the resource group and storage account that our blob object lives in:

PS BlogScripts:> $StorageAccount = Get-AzureRmStorageAccount -ResourceGroupName 'nrdcfgstore' -Name 'nrdcfgstoreacct'

Once you’ve got your storage account, we can then acquire the storage account key, like we did in our last blog.


$StorageKey = (Get-AzureRmStorageAccountKey -ResourceGroupName $StorageAccount.ResourceGroupName -Name $StorageAccount.StorageAccountName)[0]

And then once we have our key, we can get the storage context and access our container:


$StorContext = New-AzureStorageContext -StorageAccountName $StorageAccount.StorageAccountName -StorageAccountKey $StorageKey.Value$Containers = Get-AzureStorageContainer -Context $StorContext -Name 'json'

And now we can get our object inside of the container:

 $TargetObject = (Get-AzureStorageBlob -Container $Containers.Name -Context $StorContext).where({$PSItem.Name -eq 'AzureDSCDeploy.json'})

And finally, we can get our SAS Token URI. Note, that I’m using HTTPSOnly for the protocol, r (Read-Only) for the permission, setting an immediate start time, and then limiting the time allowed for one hour with the ExpiryTime parameter. This ensures that the object will only be accessible for an hour after the command is run via HTTPS.


$SASToken = New-AzureStorageBlobSASToken -Container $Containers.Name -Blob $TargetObject.Name -Context $StorContext -Protocol 'HttpsOnly' -Permission r -StartTime (Get-Date) -ExpiryTime (Get-Date).AddHours(1) -FullUri

So by comparison, if I tried to access the direct URL of the object, this is what I’ll get:

However, with my SAS Token URL, I can successfully read the file:

And we’re done!

“So where is this useful in automation?” you may ask. Well I’ll be showing you exactly how next week when we take the code that we’ve built for the last couple of weeks and use it to deploy an Azure template via Azure automation.

See you then!