Create Azure Blob Storage SAS tokens

An Azure blob SAS (Shared Access Signature) token is used in many places in order to access either a specific blob or a container. It’s simply a string made up of your storage account name and your storage account key. The whole point of the SAS token is that you can share it with anyone you like to give them access to blob storage without compromising your real underlining storage account key. The SAS token is in a format which can be used in a URI/URL. It is not a certificate and is not stored anywhere, it’s purely created/constructed and used straight after – and is normally stored in memory as part of a variable or can be shared with others and can contain an expiry date. More info here.

Below is a PowerShell script which you can use to help construct an Azure blob storage SAS token – this one focuses on grating access to blob containers.

# Login to Azure manually
Clear-AzureRmContext Scope CurrentUser Force
LoginAzureRmAccount TenantId '<Your Azure Tenant ID>' # Microsoft
### Choose Subscription
$subscription = Get-AzureRmSubscription | Out-GridView Title "Select the Azure subscription that you want to use …" PassThru
Select-AzureRmSubscription SubscriptionId $
# Fill in these variables
$StorageAccountName = '<YourStorageAccountName>'
$StorageContainerName = '<YourStorageContainerName>'
$StorageAccountKey = '<YourStorageAccountKey>'
$BlobName = '/SomeFolder/file.ext' # this is to construct the SAS URI below so you can test
$StgContext = New-AzureStorageContext StorageAccountName $StorageAccountName StorageAccountKey $StorageAccountKey
$StartTime = Get-Date
$EndTime = $startTime.AddHours(5.0)
# Read access –
$SasToken = New-AzureStorageContainerSASToken Name $StorageContainerName `
Context $StgContext Permission rl StartTime $StartTime ExpiryTime $EndTime
$SasToken | clip
# Construnct the URL & Test
$url = "$($StgContext.BlobEndPoint)$($StorageContainerName)$($BlobName)$($SasToken)"
$url | clip
Invoke-WebRequest UseBasicParsing Uri $url | Out-Null

Leave a Reply

Please log in using one of these methods to post your comment: Logo

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

Google photo

You are commenting using your Google 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