I am trying to generate a SAS token for a Blob Storage account using C#. However, I’m encountering an error when trying to authenticate the request:
<Error>
<Code>AuthenticationFailed</Code>
<Message>Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
RequestId:0ead0723-901e-002c-7b88-037068000000 Time:2024-09-10T13:52:02.2658050Z</Message>
<AuthenticationErrorDetail>Signature fields not well formed.</AuthenticationErrorDetail>
</Error>
To clarify, I am trying to generate the SAS token without using the NuGet package “Azure.Storage.Blobs”. I managed to generate the SAS token successfully using the library, but now I want to achieve the same result purely with APIs. Below is the code I’m using to generate the SAS token:
private string GenerateSasToken(string accountName, string accountKey, string containerName, string blobName)
{
// Define SAS parameters
string signedPermissions = "r"; // Read permissions
string signedStart = DateTime.UtcNow.AddMinutes(-5).ToString("yyyy-MM-ddTHH:mm:ssZ"); // Start time is 5 minutes ago to account for clock skew
string signedExpiry = DateTime.UtcNow.AddHours(8).ToString("yyyy-MM-ddTHH:mm:ssZ"); // Expiry time 8 hours from now
string signedResource = "b"; // Blob resource type
string signedVersion = "2022-11-02"; // Storage service version
string signedProtocol = "https"; // HTTPS only
string signedIp = ""; // No IP restriction
// Canonicalized resource: "/blob/account/container/blob"
string canonicalizedResource = $"/blob/{accountName}/{containerName}/{blobName}";
// Construct the string-to-sign
string stringToSign = $"{signedPermissions}n" +
$"{signedStart}n" +
$"{signedExpiry}n" +
$"{canonicalizedResource}n" +
$"n" + // signedIdentifier (optional, left empty)
$"{signedIp}n" +
$"{signedProtocol}n" +
$"{signedVersion}n";
// Decode the account key from Base64
byte[] keyBytes = Convert.FromBase64String(accountKey);
// Create HMAC-SHA256 hash
using (HMACSHA256 hmac = new HMACSHA256(keyBytes))
{
byte[] signatureBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));
string signature = Convert.ToBase64String(signatureBytes);
// Construct the SAS token
var sasToken = HttpUtility.ParseQueryString(string.Empty);
sasToken["sp"] = signedPermissions;
sasToken["st"] = signedStart;
sasToken["se"] = signedExpiry;
sasToken["spr"] = signedProtocol;
sasToken["sv"] = signedVersion;
sasToken["sr"] = signedResource;
sasToken["sig"] = HttpUtility.UrlEncode(signature); // URL-encoded signature
// Return the full blob URL with the SAS token
return $"https://{accountName}.blob.core.windows.net/{containerName}/{blobName}?{sasToken}";
}
}
Problem:
I am getting the error that the signature fields are not well-formed. This seems to indicate that there is an issue with how the string-to-sign or the signature itself is being constructed. Does anyone have experience with this error, or can you spot anything wrong with my code?
Any help or advice would be greatly appreciated!
I really appreciate any help you can provide.
2
To clarify, I am trying to generate the SAS token without using the NuGet package “Azure.Storage.Blobs”. I managed to generate the SAS token successfully using the library, but now I want to achieve the same result purely with APIs.
You can use the below code to generate SAS
token with API request using C#.
Code:
using System;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Web;
class Program
{
// Function to generate SAS token
static string GenerateSas(string storageAccountKey, string input)
{
var keyBytes = Convert.FromBase64String(storageAccountKey);
var inputBytes = Encoding.UTF8.GetBytes(input);
using (var hmacSha256 = new HMACSHA256(keyBytes))
{
var hashBytes = hmacSha256.ComputeHash(inputBytes);
var hashBase64 = Convert.ToBase64String(hashBytes);
var hashB64UriEncoded = HttpUtility.UrlEncode(hashBase64);
return hashB64UriEncoded;
}
}
static void GenerateSasToken(string blobName,string accessKey,string containerName)
{
var currentDate = DateTime.UtcNow;
var expiration = currentDate.AddMinutes(120);
var signedStart = currentDate.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
var signedExpiry = expiration.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
string signedPermissions = "rwl";
string signedService = "b"; // 'b' for blob
string signedProtocol = "https";
string signedVersion = "2022-11-02";
string accountname = "venkat326123";
// Include the blob name in the canonicalized resource
var canonicalizedResource = $"/blob/{accountname}/{containerName}/{blobName}";
var stringToSign = $"{signedPermissions}n{signedStart}n{signedExpiry}n{canonicalizedResource}nnn{signedProtocol}n{signedVersion}n{signedService}nnnnnnn";
var signature = GenerateSas(accessKey, stringToSign); // Generate signature using GenerateSas function
var sasToken = $"sv={signedVersion}&sr={signedService}&sp={signedPermissions}&st={signedStart}&se={signedExpiry}&spr={signedProtocol}&sig={signature}";
Console.WriteLine(sasToken);
Console.WriteLine($"https://{accountname}.blob.core.windows.net/{containerName}/{blobName}?{sasToken}");
}
static void Main()
{
string blobName = "example.png";
string containerName = "test";
string accessKey = "T3czZxxxx";
GenerateSasToken(blobName,accessKey,containerName);
}
}
Output:
sv=2022-11-02&sr=b&sp=rwl&st=2024-09-11T07:54:36Z&se=2024-09-11T09:54:36Z&spr=https&sig=Tmvk1aF4Nh8xxxxx3d
https://venkat326123.blob.core.windows.net/test/example.png?sv=2022-11-02&sr=b&sp=rwl&st=2024-09-11T07:54:36Z&se=2024-09-11T09:54:36Z&spr=https&sig=Tmxxxxx8%3d
I Copied and pasted the Blob SAS URL in the browser. It showed the image successfully.
Browser: