Managed Storage Account SAS Tokens

Azure Infrastructure

Introduction

Building on the previous blog post where we configured Azure Key Vault to automatically rotate Storage Account Keys, this post will discuss SAS tokens (Shared Access Signatures). As a quick refresher, using SAS tokens is the recommended way to interact with your Storage Account. For more information see Using shared access signatures.

Create SAS Definition

In order to create a SAS definition, you will need the setsas permission. We can add this to the list of permissions we used in the previous blog post:

Set-AzureRmKeyVaultAccessPolicy -VaultName $keyVaultName -ResourceGroupName $keyVaultResourceGroupName -UserPrincipalName $upn -PermissionsToStorage set, get, regeneratekey, setsas

Now, we can create a SAS definition. For my example, I want to:

  • Limit the SAS definition the Blob service (and not Tables, Queues, or Files).
  • Name it sas1
  • Limit to https only
  • Limit to only my current IP address (IP whitelist)
  • Limit the validity of the token to 5 days
  • Limit the permissions to Read and Write.

In the command below, I’m first getting my IP address using ipinfo.io site. Then I’m using the Set-AzureKeyVaultManagedStorageSasDefinition to create a new definition.

$ip = Invoke-RestMethod http://ipinfo.io/json | Select -ExpandProperty ip
$sasDefinition = Set-AzureKeyVaultManagedStorageSasDefinition `
-Service Blob `
-ResourceType Container,Object `
-VaultName $keyVaultName `
-AccountName $storageAccountName `
-Name 'sas1' `
-Protocol HttpsOnly `
-IPAddressOrRange $ip `
-ValidityPeriod ([System.Timespan]::FromDays(5)) `
-Permission Write,Read

Once you do this, you’ll see a new secret in your Key Vault. Now, let’s get the secret value.

$secret = Get-AzureKeyVaultSecret -VaultName $keyVaultName -Name ($sasDefinition.sid).Split("/")[-1]
$sasToken = $secret.SecretValueText

Use SAS Definition

That’s it! Now, let’s test this by uploading a file. There’s nothing new here, I’m simply using Set-AzureStorageBlobContent with a context. The context is generated from the SAS token we retrieved in the previous step.

$container = "docs"
$localFile = "C:\Temp\FUNDAMENTALS OF AZURE 2ND ED.pdf"
$blobName = "Fundamentals of Azure.pdf"
$ctx = New-AzureStorageContext -SasToken $sasToken -StorageAccountName $storageAccountName
Set-AzureStorageBlobContent -File $localFile -Container $container -Blob $blobName -Context $ctx –Verbose

There could be many use cases for this. For example, if several users need to upload files to blob storage, you can generate a unique SAS for each one. Another example could be an application querying Key Vault to get a SAS token. This one is documented on the official documentation here.

0 comments… add one

Leave a Reply