azure - Download blob from Azure Storage with SAS
问题描述
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");
}
}
解决方案
在官方 github 存储库中,您可以找到使用各种身份验证方式的绝佳示例。在示例中使用帐户密钥称为 SharedKey。还有一个使用 SAS 令牌的示例- 但您需要以某种方式生成这些令牌。通常您使用帐户密钥执行此操作...
另一种选择——如果可能的话,我建议使用的是基于 AAD(Azure Active Directory)的 aut h。在这种情况下,您不需要帐户密钥或 SAS 令牌。
有关各种示例,请参见此处: https ://github.com/Azure/azure-sdk-for-net/blob/master/sdk/storage/Azure.Storage.Blobs/samples/Sample02_Auth.cs
推荐阅读
- r - 如何为自定义 S3 类实现提取/子集([、[<-、[[、[[<-)] 函数?
- wordpress - 如何在我的 codeigniter 控制器中从 wordpress DB 获取最近的帖子?
- r - 如何计算向量中的重复条目?
- extjs - Sencha 6.5.2(现代)带小数分隔符的数字字段
- cassandra - Nosql之类的bigtable是如何存储Image数据的?
- bootstrap-4 - 车身高度 100% 与引导容器和 flex 冲突
- java - Recyclerview 点击条件
- python - 将字符串列表正确格式化为python中的日期列表
- sql - 选择价格不是最高价格的结果
- nginx - nginx根据子路径添加header