1
votes

I am having a hard time figuring out how to download a blob from Azure storage using .net and a generated Shared Access Signature token.

First of all, most of the tutorials I could find are using Microsoft.Azure.Management.Storage nuget package, which is deprecated. Instead I use the newest Azure.Storage.Blobs package.

I have the following code so far. I don't know what to do with the generated SAS token. How do I download the blob from there ?

  [HttpGet]
    public async Task<IActionResult> Download([FromQuery] string blobUri)
    {
        BlobServiceClient blobServiceClient = new BlobServiceClient(this.configuration.GetConnectionString("StorageAccount"));


        // Create a SAS token that's valid for one hour.
        BlobSasBuilder sasBuilder = new BlobSasBuilder()
        {
            BlobContainerName = "my container name",
            BlobName = blobUri,
            Resource = "b",
            StartsOn = DateTimeOffset.UtcNow,
            ExpiresOn = DateTimeOffset.UtcNow.AddHours(1)
        };

        // Specify read permissions for the SAS.
        sasBuilder.SetPermissions(BlobSasPermissions.Read);

        // Use the key to get the SAS token.
        var sasToken = sasBuilder.ToSasQueryParameters(new Azure.Storage.StorageSharedKeyCredential("my account name", "my account key"));



        BlobClient blob = blobServiceClient.GetBlobContainerClient("my container name").GetBlobClient($"{blobUri}");
        await using (MemoryStream memoryStream = new MemoryStream())
        {
            await blob.DownloadToAsync(memoryStream);
           return File(memoryStream, "file");
        }

    }
1
If I understand correctly, you would want to download blob using SAS URI. Correct? Also, what's the blobUri parameter? Is it the name of the blob or it's URL?Gaurav Mantri
if you already have the account key in there, why do you want to generate a SAS token? why not just using the key to download?silent
@GauravMantri-AIS, correct. And the blobUri parameter is the blog URL.Sam
@silent, I'm not sure how to use the account key to download the file ? Besides, this is just a POC for now, I will eventually remove this key from the source code and I want to use SAS token as a more secured waySam
Sam...You can't really get rid of account key as it is required to generate a SAS token.Gaurav Mantri

1 Answers

0
votes

In the official github repo you find great example using various means of authentication. Using account key in the sample is called SharedKey. There is also a sample to use SAS tokens - but those you need to generate somehow. Usually you do this using the account key...

The other option - and what I would recommend to use if possible, is to use AAD (Azure Active Directory)-based auth. In this case you don't need either account keys or SAS tokens.

See here for the various samples: https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/storage/Azure.Storage.Blobs/samples/Sample02_Auth.cs