【问题标题】:Download blob from Azure Storage with SAS使用 SAS 从 Azure 存储下载 blob
【发布时间】:2020-10-05 20:32:29
【问题描述】:

我很难弄清楚如何使用 .net 和生成的共享访问签名令牌从 Azure 存储下载 blob。

首先,我能找到的大多数教程都使用Microsoft.Azure.Management.Storage nuget 包,该包已被弃用。相反,我使用最新的 Azure.Storage.Blobs 包。

到目前为止,我有以下代码。我不知道如何处理生成的 SAS 令牌。如何从那里下载 blob?

  [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");
        }

    }

【问题讨论】:

  • 如果我理解正确,您可能希望使用 SAS URI 下载 blob。正确的?另外,blobUri 参数是什么?它是 blob 的名称还是它的 URL?
  • 如果您已经拥有帐户密钥,为什么要生成 SAS 令牌?为什么不直接使用密钥下载?
  • @GauravMantri-AIS,正确。而 blobUri 参数是博客 URL。
  • @silent,我不知道如何使用帐户密钥下载文件?此外,这只是一个 POC,我最终会从源代码中删除这个密钥,我想使用 SAS 令牌作为更安全的方式
  • Sam...您无法真正摆脱帐户密钥,因为它是生成 SAS 令牌所必需的。

标签: azure azure-storage azure-blob-storage azure-sdk-.net


【解决方案1】:

在官方 github 存储库中,您可以找到使用各种身份验证方式的绝佳示例。使用sample is called SharedKey 中的帐户密钥。还有一个sample to use SAS tokens - 但你需要以某种方式生成。通常您使用帐户密钥来执行此操作...

另一个选项——如果可能的话,我建议使用的是AAD (Azure Active Directory)-based auth。在这种情况下,您不需要帐户密钥或 SAS 令牌。

请参阅此处了解各种示例: https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/storage/Azure.Storage.Blobs/samples/Sample02_Auth.cs

【讨论】:

  • 是的,我已经看过这些示例,如果您检查我的代码,您会发现我正在使用相同的方法。我的问题与从 blob 容器中实际下载文件有关。如何使用生成的 SAS 令牌下载文件?
猜你喜欢
  • 1970-01-01
  • 2021-04-29
  • 2013-01-21
  • 1970-01-01
  • 2015-06-20
  • 2022-11-02
  • 2019-12-19
  • 2019-09-05
  • 2014-08-09
相关资源
最近更新 更多