简体   繁体   English

Azure Blob 存储 SAS 令牌未正确形成 .NET

[英]Azure Blob Storage SAS Token not formed properly .NET

I am trying to generate an SaS token to download a blob from Azure Blob Storage.我正在尝试生成 SaS 令牌以从 Azure Blob 存储下载 Blob。 After generating the token and attempting to download I am met with the following error:生成令牌并尝试下载后,我遇到了以下错误:

Azure.RequestFailedException
  HResult=0x80131500
  Message=Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
RequestId:6127b736-401e-002d-7413-aeddd5000000
Time:2020-10-29T16:53:15.3700463Z
Status: 403 (Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.)
ErrorCode: AuthenticationFailed

This is the token generated by the dashboard in Azure:这是 Azure 中仪表板生成的令牌:

sp=r&st=2020-10-29T16:59:18Z&se=2020-10-29T17:59:18Z&spr=https&sv=2019-12-12&sr=b&sig=KEXuzAqhUOxwvJeGAeCxJ%2BroF2D7VDnx%2BgM7ABuch%2Fs%3D

This is my generated token:这是我生成的令牌:

sv=2019-12-12&spr=https&st=2020-10-29T16:53:51Z&se=2020-10-29T22:53:51Z&sr=b&sp=r&sig=RsVzWh/QlRtMTDUXtVVKJ3WAkCjrpr2CRXN1idEyWdc=

Here is my code used to generate the token:这是我用于生成令牌的代码:

    private static Uri GetBlobSasUri(BlobContainerClient container,
                string blobName, StorageSharedKeyCredential key, string storedPolicyName = null)
    {
        // Create a SAS token that's valid for one hour.
        BlobSasBuilder sasBuilder = new BlobSasBuilder()
        {
            BlobContainerName = container.Name,
            BlobName = blobName,
            Resource = "b",
            Protocol = SasProtocol.Https,
        };

        if (storedPolicyName == null)
        {
            sasBuilder.StartsOn = DateTimeOffset.UtcNow;
            sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(6);
            sasBuilder.SetPermissions(BlobContainerSasPermissions.Read);
        }
        else
        {
            sasBuilder.Identifier = storedPolicyName;
        }

        // Use the key to get the SAS token.
        BlobSasQueryParameters parameters = sasBuilder.ToSasQueryParameters(key);
        string sasToken = Uri.UnescapeDataString(parameters.ToString());

        Console.WriteLine("SAS for blob is: {0}", sasToken);
        Console.WriteLine();

        UriBuilder baseUri = new UriBuilder(container.GetBlockBlobClient(blobName).Uri);
        baseUri.Query = sasToken;

        return baseUri.Uri;
    }

I figured out the problem.我解决了这个问题。

  1. The signature needed to be UrlEncoded签名需要 UrlEncoded
  2. I needed to set the StartsOn offset to DateTimeOffset.UtcNow.AddMinutes(-5)我需要将 StartsOn 偏移量设置为DateTimeOffset.UtcNow.AddMinutes(-5)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM