且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Azure存储SAS身份验证失败

更新时间:2023-12-03 15:08:16

我也无法使用代码重现该问题.这是一种无需使用GetSharedAccessSignature方法即可生成SAS的方法.请尝试一下,然后检查它是否可以在您身边使用.

I also can't reproduced the issue using the code. Here is a method which could generate SAS without using the GetSharedAccessSignature method. Please try it and check whether it can work on your side.

private static string GetSharedAccessSignature(
       string accountName,
       string accountkey,
       string blobContainer,
       string blobName,
       DateTimeOffset sharedAccessStartTime,
       DateTimeOffset sharedAccessExpiryTime)
{
    var canonicalNameFormat = $"/blob/{accountName}/{blobContainer}/{blobName}";
    var st = sharedAccessStartTime.UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ssZ");
    var se = sharedAccessExpiryTime.UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ssZ");
    var sasVersion = "2016-05-31";

    string stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n{9}\n{10}\n{11}\n{12}", new object[]
    {
        "r",
        st,
        se,
        canonicalNameFormat,
        string.Empty,
        string.Empty,
        string.Empty,
        sasVersion,
        string.Empty,
        string.Empty,
        string.Empty,
        string.Empty,
        string.Empty
    });

    var sas = GetHash(stringToSign, accountkey);

    var credentials =
        $"?sv={sasVersion}&sr=b&sig={UrlEncoder.Default.Encode(sas)}&st={UrlEncoder.Default.Encode(st)}&se={UrlEncoder.Default.Encode(se)}&sp=r";

    string blobUri = $"https://{accountName}.blob.core.windows.net/{blobContainer}/{blobName}";
    return blobUri + credentials;
}

private static string GetHash(string stringToSign, string key)
{
    byte[] keyValue = Convert.FromBase64String(key);

    using (HMACSHA256 hmac = new HMACSHA256(keyValue))
    {
        return Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
    }
}