I'm having some problems generating SAS token to download the file of Azure Storage. The following produces a URI that does not work. The error message I get back is Signature did not match
, and I'm uncertain why.
Has anyone generated SAS tokens, and got the signature to match manually?
static void Main(string[] args)
{
var sas = generateSAS
(
key, // Azure portal very secret ^-^
keyName, // Azure portal, example: key1
resourceUri, // example: https://myaccount.blob.core.windows.net/emails/email.pdf
resourcePath // example: /blob/myaccount/emails/email.pdf
);
}
private static string generateSAS(string key, string keyName, string uri, string path)
{
var permissions = "r";
var startTime = DateTime.UtcNow;
var endTime = DateTime.UtcNow.AddSeconds(60 * 2);
var canonicalizedresource = path;
var signedidentifier = keyName;
var signedversion = "2012-02-12";
var stringToSign = permissions + "\n" +
startTime.ToUniversalTime().ToString("u").Replace(" ", "T") + "\n" +
endTime.ToUniversalTime().ToString("u").Replace(" ", "T") + "\n" +
canonicalizedresource + "\n" +
signedidentifier + "\n" +
signedversion;
HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));
var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
return string.Format(CultureInfo.InvariantCulture, "{0}?sp={1}&st={2}&se={3}&spr={4}&sv={5}&sr={6}&si={7}&sig={8}",
uri,
permissions,
startTime.ToUniversalTime().ToString("u").Replace(" ", "T"),
endTime.ToUniversalTime().ToString("u").Replace(" ", "T"),
"https",
signedversion,
"b",
keyName,
HttpUtility.UrlEncode(signature));
}