28 Apr 2024
TLDR: video
In the midst of building a webshop-like feature for the kiss-code.com brand website, I stumbled upon the requirement to provide protected access to the digital products.
Currently, my shop only holds the lead magnet which is free. Within 5 minutes after ordering it, you should receive an email containing a download link. This lead magnet lives on an Azure Blob Storage container which allows public read access for anyone to download, at any time.
This download link getting leaked would result in people bypassing subscribing to my newsletter. So, let's start by changing the access level to private.
Surprise! Changing the access level to private will deny access also to the people who should have access after subscribing. Now, we can generate Shared Access Signature (SAS) tokens to grant limited access for a limited time. We can simply generate one by specifying permissions and the token's time-to-live (expiry) and clicking that "Generate SAS token and URL" button.
This results in the following token and URL. Following that URL will download the lead magnet which lives in a private Azure Blob Storage container.
Now, I'll want to generate these URLs automatically after someone ordered a digital product on my shop. So that this person receives an email containing the download link including the SAS token to access the purchased product.
I'll add the following code to my NuGet package to generate an URL including a SAS token that grants read access for a given duration.
public string GenerateSasUrlForBlob(string blobName, DateTimeOffset? expiresOn = null, string? containerName = null)
{
ArgumentNullException.ThrowIfNullOrWhiteSpace(_config.AccountKey);
containerName = string.IsNullOrWhiteSpace(containerName) ? _config.ContainerName : containerName;
ArgumentNullException.ThrowIfNullOrWhiteSpace(containerName);
var sasBuilder = new BlobSasBuilder
{
BlobName = blobName,
BlobContainerName = containerName,
ExpiresOn = expiresOn ?? DateTimeOffset.UtcNow.AddHours(24)
};
sasBuilder.SetPermissions(BlobSasPermissions.Read);
var sasUrl = sasBuilder
.ToSasQueryParameters(new StorageSharedKeyCredential(_config.AccountName, _config.AccountKey))
.ToString();
return sasUrl;
}
You can get an AccountKey
in the Azure portal:
Find my .NET 8 Brand Website V1 with tons of features add value to and capture your audience!
If you are interested in more of my work, you can find it:
Thank you for taking the time & interest in my work. Kind regards, Auguste @ kiss-code.com
Sources:
I continuously build, learn and experiment with innovative technology. Allow me to share what I learn, with you.
Allow me to share what I learn, with you.
Unlock access to source code behind each article, here.