Azure Blob Storage SAS Token not formed properly .NET

0

I am trying to generate an SaS token to download a blob from Azure Blob Storage. 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:

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;
    }
c#
.net
azure
azure-storage-blobs
asked on Stack Overflow Oct 29, 2020 by Daniel Osmond

1 Answer

0

I figured out the problem.

  1. The signature needed to be UrlEncoded
  2. I needed to set the StartsOn offset to DateTimeOffset.UtcNow.AddMinutes(-5)
answered on Stack Overflow Oct 29, 2020 by Daniel Osmond

User contributions licensed under CC BY-SA 3.0