Click here to Skip to main content
15,881,852 members
Articles / Hosted Services / Azure
Technical Blog

Articles: Generate SAS token to access Azure Storage

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
8 Feb 2020CPOL2 min read 2.5K   1   2
When you create an Azure Storage account to store files in a container you can set the permissions to what ever access level you want, and you can generate tokens to access the blob storage account with set periods of time. That’s what we’re going to do here today.. 0.

This article is an entry in our Windows Azure Developer Challenge. Articles in this sub-section are not required to be full articles so care should be taken when voting. Create your free Azure Trial Account to Enter the Challenge.

When you create an Azure Storage account to store files in a container you can set the permissions to what ever access level you want, and you can generate tokens to access the blob storage account with set periods of time. That’s what we’re going to do here today.

0. Login to your Azure account

Lets first login to your Azure Account using the Login-AzureRmAccount command. A prompt asking for email address, and then password will popup.

<code class="language-PowerShell">Login-AzureRmAccount
</code>

1. Create a new Resource Group

Now we need to create a new Resource Group for our storage account to live in. The naming of this can be anything you like.

<code class="language-PowerShell">$resourceGroupName = "NewResourceGroup"
$location = "West Europe"

New-AzureRmResourceGroup -Name $resourceGroupName -Location $location -Verbose -Force
</code>

2. Create a new Storage Account

Now for the creation of the actual storage account, the name for this needs to be globally unique in the whole of Azure. This is because it has a URL to access it, so you will need to change the below storageAccountName or you will receive an error.

<code class="language-PowerShell">$storageAccountName = "storageaccountsas"

New-AzureRmStorageAccount -Name $storageAccountName -ResourceGroupName $resourceGroupName -Location $location -SkuName "Standard_LRS"
</code>

3. Upload a file

We’re going to create a txt file with some text in, create a container (which is just a like a folder structure) in our storage account, then upload the individual file we just created.

<code class="language-PowerShell">echo some-text  > filename.txt

$containerName = "upload"
$storageAccount = (Get-AzureRmStorageAccount | Where-Object{$_.StorageAccountName -eq $storageAccountName})
New-AzureStorageContainer -Name $containerName -Context $storageAccount.Context -ErrorAction SilentlyContinue *>&1

$folderPath = (Get-Item -Path ".\" -Verbose).FullName
$SourcePath = $folderPath + "\filename.txt"

Set-AzureStorageBlobContent -File $SourcePath -Blob $SourcePath.Substring($folderPath.length + 1) -Container $containerName -Context $storageAccount.Context -Force | out-null
</code>

4. Generate a SAS token for 12 hours

Now that we have our file uploaded, we need to generate a SAS token for to access our file, we’re going to set the expiry of this to 12 hours, but this can be changed to whatever you need.

<code class="language-PowerShell">Set-AzureRmCurrentStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccountName | out-null
$sasToken = New-AzureStorageContainerSASToken -Name $containerName -Permission r -Protocol HttpsOnly -ExpiryTime (Get-Date).AddHours(12)

$sasToken
</code>

Test we can access it with SAS token

First lets test that the file is still private and not accessable to the public.

Open a new browser window and try browsing to http://storageaccountsas.blob.core.windows.net/upload/filename.txt

You should be greated with the following message:

<code class="language-XML"><Error>
<Code>ResourceNotFound</Code>
<Message>
The specified resource does not exist. RequestId:86e3247c-101e-00fa-37d7-060e24000000 Time:2018-06-18T07:41:07.3620454Z
</Message>
</Error>
</code>

Azure is giving nothing away here, it just says resource does not exist, as you do not have the permissions to access it.

Test with the new SAS Token

If you open up a new browser and type in the location of the newly uploaded file with the sasToken added to the end, mine is https://storageaccountsas1.blob.core.windows.net/upload/filename.txt?sv=2017-07-29&sr=c&sig=tG3bkXUNUxGa3IwXosTgweQo7XAOChPF4%2FCdYTm4%2Fmc%3D&spr=https&se=2018-06-18T19%3A44%3A40Z&sp=r

It should now download the filename.txt to your computer.

The whole script

<code class="language-PowerShell">### 1. CREATE A NEW RESOURCE GROUP
$resourceGroupName = "NewResourceGroup"
$location = "West Europe"

New-AzureRmResourceGroup -Name $resourceGroupName -Location $location -Verbose -Force

### 2. CREATE A NEW STORAGE ACCOUNT
$storageAccountName = "storageaccountsas"

New-AzureRmStorageAccount -Name $storageAccountName -ResourceGroupName $resourceGroupName -Location $location -SkuName "Standard_LRS"

### 3. UPLOAD A FILE
echo some-text  > filename.txt

$containerName = "upload"
$storageAccount = (Get-AzureRmStorageAccount | Where-Object{$_.StorageAccountName -eq $storageAccountName})
New-AzureStorageContainer -Name $containerName -Context $storageAccount.Context -ErrorAction SilentlyContinue *>&1

$folderPath = (Get-Item -Path ".\" -Verbose).FullName
$SourcePath = $folderPath + "\filename.txt"

Set-AzureStorageBlobContent -File $SourcePath -Blob $SourcePath.Substring($folderPath.length + 1) -Container $containerName -Context $storageAccount.Context -Force | out-null

### 4. GENERATE A SAS TOKEN FOR 12 HOURS
Set-AzureRmCurrentStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccountName | out-null
$sasToken = New-AzureStorageContainerSASToken -Name $containerName -Permission r -Protocol HttpsOnly -ExpiryTime (Get-Date).AddHours(12)

$sasToken
</code>

Conclusion

SAS Tokens can be used throughout your powershell scripts and within your ARM templates to access files in your storage account, often other commands will have a -sastoken property.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
United Kingdom United Kingdom
I have been working in software development for over 16 years, during that time I have worn many hats.

I have worked as a Software Engineer, Architect, Agile Coach and Trainer. I’ve created teams, I’ve lead teams, but my main goal is to help teams build great software and enjoy the process.

I help a whole range of businesses – from startups with just an idea who want to build a team to take that idea into reality and FTSE 100 businesses who need to optimise existing teams – I train, mentor and coach them to success.

If you happen to know of anybody who could benefit from results like this, then please go to my contact page and get in touch.

Owen Davies

Comments and Discussions

 
PraiseBusy Beyond Belief Pin
John Avellani30-Jun-22 9:55
John Avellani30-Jun-22 9:55 
PraiseBusy Beyond Belief Pin
John Avellani30-Jun-22 9:55
John Avellani30-Jun-22 9:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.