When working with cloud storage, there are several ways to secure access to your resources, and one common approach is using a Shared Access Signature (SAS) token. SAS tokens allow controlled, limited-time access to Azure Blob Storage without exposing sensitive credentials. In this post, I’ll walk through how I used Python to upload files to Azure Blob Storage with a SAS token.
Thank me by sharing on Twitter 🙏
Why Use SAS Tokens?
Before diving into the implementation, it’s important to understand why SAS tokens are useful. When managing cloud storage, particularly in environments where multiple services or users interact with resources, maintaining security while allowing flexible access is critical. A SAS token provides a fine-grained control mechanism over who can access storage resources and what they can do with them. You can control permissions like read, write, delete, and even set expiration dates for the token’s validity.
In my experience, SAS tokens make it easy to integrate with external services without exposing sensitive credentials, such as the account’s primary key, while ensuring that security boundaries remain intact.
Getting Started: Understanding the Problem
I recently needed to upload files to Azure Blob Storage from a Python script, but instead of using a full connection string (which might expose sensitive information), I was provided a SAS token. This SAS token contained the necessary permissions for the container in which I wanted to store my files. However, while using the SAS token, I encountered a challenge: directly constructing the blob URL to upload files successfully.
The SAS Token
The SAS token I received looked like this:
iPhone Charger 3 Pack 10 ft Apple MFi Certified Lightning Nylon Braided Cable Fast Charging Cord Compatible with iPhone 13 12 11 Pro Max XR XS X 8 7 6 Plus SE iPad and More
$9.99 (as of December 21, 2024 08:38 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)Anker USB to USB C Cable [2 Pack, 3FT], USB A to USB C Charger Cord for Samsung Galaxy S10 S10+, LG V30, Beats Fit Pro and More (USB 2.0, Black)
$8.99 (as of December 21, 2024 08:38 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)The Coming Wave: Technology, Power, and the Twenty-First Century's Greatest Dilemma
$17.72 (as of December 21, 2024 19:39 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)https://mystuff.blob.core.windows.net/some-path?sp=racw&st=2020-01-01T00:00:00Z&se=2020-01-01T00:00:00Z&spr=https&sv=2025-01-01&sr=c&sig=ZZZZZZZ
The token URL consists of:
- Base URL: This points to the Azure Blob Storage container.
- SAS Parameters: These parameters, starting with
sp
, define permissions and expiration time.
However, I noticed that this token points to the container (media
), not directly to a specific blob (file). To upload a file, I needed to construct the full blob URL by appending the file name (blob name) to the container’s base URL.
Uploading Files with Python
To upload files to Azure Blob Storage using Python, I used the azure-storage-blob
library. Here’s how I tackled the problem and got the files successfully uploaded.
Step 1: Installing the Required Library
Since I was working with Azure Blob Storage, I needed the azure-storage-blob
package. This package allows interaction with blob storage, enabling you to upload, download, and manage blobs.
pip install azure-storage-blob
This library provides all the necessary tools for working with Azure Blob Storage in Python.
Step 2: Constructing the Full Blob URL
With the SAS token pointing only to the container, I needed to modify the URL to target a specific blob (file). The solution was simple: append the file name to the container’s URL, like so:
https://mystuff.blob.core.windows.net/some-path/your-blob-name?sp=racw&st=2020-01-01T00:00:00Z&se=2020-01-01T00:00:00Z&spr=https&sv=2025-01-01&sr=c&sig=ZZZZZZZ
This full URL now points to the specific blob (your-blob-name
) where I wanted to upload the file.
Step 3: Uploading the File
Now that I had the full URL, the next step was creating a simple Python script to handle the upload.
Here’s the script that I used to upload my file using the SAS token:
from azure.storage.blob import BlobClient
# Define the base SAS token URL (container level)
blob_name = "your-blob-name" # Name of the blob to upload to (e.g., "myfile.txt")
file_path = "path/to/your/local/file" # Path to the file on your local machine
# Construct the full blob URL by appending the blob name to the SAS URL (before the `?`)
blob_url = f"https://myprod.blob.core.windows.net//some-path/{blob_name}?sp=racw&st=2020-01-01T00:00:00Z&se=2020-01-01T00:00:00Z&spr=https&sv=2025-01-01&sr=c&sig=ZZZZZZZ"
# Create a BlobClient object using the full blob URL
blob_client = BlobClient.from_blob_url(blob_url)
# Upload the file
with open(file_path, "rb") as data:
blob_client.upload_blob(data)
print(f"File {file_path} uploaded to {blob_name} in the container.")
This script does a few important things:
- Constructs the Full Blob URL: It appends the blob (file) name to the container URL provided by the SAS token.
- Creates a
BlobClient
Object: TheBlobClient
is used to interact directly with the blob. - Uploads the File: The file is opened in binary mode (
"rb"
) and uploaded to Azure Blob Storage usingupload_blob()
.
Step 4: Handling Errors
While working with Azure Blob Storage, you might encounter errors. For instance, if the container already exists, you could get an error when trying to create it again.
I my case I encountered a thrown exception with a malformed url that gave the following error:
ValueError: Invalid URL. Provide a blob_url with a valid blob and container name.
I usually handle this gracefully by adding a try-except block around container creation. Here’s how I did it:
try:
container_client.create_container()
except Exception as e:
print(f"Container already exists or encountered an error: {e}")
This ensures that the script doesn’t fail if the container already exists.
Conclusion
Working with Azure Blob Storage using SAS tokens is an effective way to manage access to your cloud resources securely. In this guide, I walked through how I uploaded files to Blob Storage using Python and a SAS token. Constructing the full blob URL was key, as the SAS token provided pointed only to the container, not the individual blob.
This approach keeps things secure and flexible, allowing you to control who can upload or interact with files in your container. With this method, I was able to securely upload files without exposing any sensitive credentials.