我需要授权签名代码才能从Blob Storage下载文件。使用Rest API

时间:2017-10-25 12:58:05

标签: azure azure-storage azure-blob-storage

我的验证码是我可能错的。
我附上我的代码请参考

  

私有const字符串FileDownloadURL =   “HTTPS:// {0} .blob.core.windows.net / {1} / {2}”;

 public async Task<string> DownloaDFileToBlob(string blobname, string downloadpath, string filename)
        {

            string Requesturl = string.Format(FileDownloadURL, storageAccount, blobname, filename);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Requesturl);
            string now = DateTime.UtcNow.ToString("R");
            string exp = DateTime.UtcNow.AddDays(1).ToString("R");
            request.Method = "GET";
            request.Headers.Add("x-ms-version", "2015-12-11");
            request.Headers.Add("x-ms-date", now);
            request.Headers.Add("x-ms-blob-type", "BlockBlob");
            request.Headers.Add("Authorization", AuthorizationHeader3(now, exp,storageAccount, blobname, filename));
            var response = await request.GetResponseAsync();

            using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
            {
                return resp.StatusCode.ToString();
            }

        }
  

我的身份验证标头添加方法

private string AuthorizationHeader3(string method, string now, HttpWebRequest request, string storageAccount, string storageKey, string containerName,string filename)
        {

            string headerResource = $"x-ms-date:{now}\nx-ms-version:2015-12-11";
            string canonicalizedResource = $"/{storageAccount}/{containerName}/{filename}\ncomp:metadata\nrestype:container\ntimeout:20";
            var contentEncoding = "";
            var contentLanguage = "";
            var contentLength = "";
            var contentMd5 = "";
            var contentType = "";
            var date = "";
            var ifModifiedSince = "";
            var ifMatch = "";
            var ifNoneMatch = "";
            var ifUnmodifiedSince = "";
            var range = "";
            var stringToSign = $"{method}\n{contentEncoding}\n{contentLanguage}\n{contentLength}\n{contentMd5}\n{contentType}\n{date}\n{ifModifiedSince}\n{ifMatch}\n{ifNoneMatch}\n{ifUnmodifiedSince}\n{range}\n{headerResource}\n{canonicalizedResource}";
            var signature = "";
            using (var hmacSha256 = new HMACSHA256(Convert.FromBase64String(storageKey)))
            {
                var dataToHmac = Encoding.UTF8.GetBytes(stringToSign);
                signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
            }
            String AuthorizationHeader = String.Format("{0} {1}:{2}", "SharedKey", storageAccount, signature);
            return AuthorizationHeader;
        }

1 个答案:

答案 0 :(得分:2)

根据Get blob API

https://myaccount.blob.core.windows.net/mycontainer/myblob
canonicalizedResource 应为$"/{storageAccount}/{containerName}/{blobName}

$"/{storageAccount}/{containerName}/{filename}\ncomp:metadata\nrestype:container\ntimeout:20";

请尝试使用以下演示代码下载blob。它在我身边正常工作。

 var account = "storageAccount";
 var accountKey = "account key";
 var container = "container name";
 var blobName = "blob name";
 var apiVersion = "2015-12-11";
 var blobUrl = $"https://{account}.blob.core.windows.net/{container}/{blobName}";
 var method = "GET";
 var now = DateTime.UtcNow.ToString("R");
 var canonicalizedHeaders = $"x-ms-date:{now}\nx-ms-version:{apiVersion }";
 var canonicalizedResource = $"/{account}/{container}/{blobName}";
 var stringToSign = $"{method}\n\n\n\n\n\n\n\n\n\n\n\n{canonicalizedHeaders}\n{canonicalizedResource}";
 var auth = CreateAuthString(account, stringToSign, accountKey);

 Uri uri = new Uri(blobUrl);
 HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);
 HttpClient client = new HttpClient();
 client.DefaultRequestHeaders.Add("x-ms-date", now);
 client.DefaultRequestHeaders.Add("x-ms-version", "2015-12-11");
 client.DefaultRequestHeaders.Add("Authorization", auth);
 HttpResponseMessage response = client.SendAsync(request).Result;
 var status = response.IsSuccessStatusCode;



 private static string CreateAuthString(string blobStorageAccount, string signStr, string blobStorageAccessKey)
   {
            string signature;
            byte[] unicodeKey = Convert.FromBase64String(blobStorageAccessKey);
            using (HMACSHA256 hmacSha256 = new HMACSHA256(unicodeKey))
            {
                byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(signStr);
                signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
            }

            var authorizationHeader = String.Format(
                CultureInfo.InvariantCulture,
                "{0} {1}:{2}",
                "SharedKey",
                blobStorageAccount,
                signature);

            return authorizationHeader;
      }

enter image description here