The following code works. My question is, is it correct? I ask because I've seen a lot of code where it either doesn't work or there are comments saying it's the wrong approach. (I think the API for this as evolved a lot of the examples are still catching up)
var connStr = config.GetConnectionString("AzureStorage");
var blobServiceClient = new BlobServiceClient(connStr);
var container = blobServiceClient.GetBlobContainerClient("organization");
var blobSasBuilder = new BlobSasBuilder
{
BlobContainerName = "organization",
BlobName = "thumbnail.png",
Resource = "b",
// if no StartsOn or ExpiresOn is specified, the SAS starts when the key is created
StartsOn = DateTimeOffset.UtcNow.AddMinutes(-5),
ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(5)
};
blobSasBuilder.SetPermissions(BlobSasPermissions.Read);
StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential
("louishowe", "abcdefg");
BlobUriBuilder sasUriBuilder = new BlobUriBuilder(container.Uri)
{
Query = blobSasBuilder.ToSasQueryParameters(sharedKeyCredential).ToString()
};
// Now we have the container SAS Uri we can use to contruct blob client for blobs in the container.
Uri containerSasUri = sasUriBuilder.ToUri();
BlobUriBuilder blobUriBuilder = new BlobUriBuilder(containerSasUri)
{
BlobName = "thumbnail.png"
};
PageBlobClient sasPageBlob = new PageBlobClient(blobUriBuilder.ToUri());
And second giant question - This requires the storage account key. If I have set managed identity for both my app service and storage account, can that be used to create the StorageSharedKeyCredential()
? Because otherwise I need to put the account key up on the server (granted in the key vault, but still better if not there at all).
My guess is it's needed because this SAS generation is all done on the client side and the key is needed to sign the parameter list.