2017-09-28 7 views
0

Azure Storage REST API에 대한 개념 증명 및 테스트를 수행했습니다. 그러나 인증 할 수 없습니다. 나는 하루 종일 독서와 조정 및 재 작성으로 노력했지만 여전히 효과가 없습니다. 나는 단계별로 문서화 단계를 밟아왔다.Azure Blob 저장소 REST API 서명

나는 이것을 관리해 준 사람을 찾고 싶습니다. 하드 코드 된 비트가 많아서 작동시키기 만하면됩니다. 나는 '어떤 계산 된 서명

사람이 어쩌면 내 얼굴을 쳐다보고 무엇을 볼 수와 동일하지 않습니다 응답에 다시 HTTP 요청'에있는

MAC 서명이 오류가 계속? 나를 미치게 만들었다.

var requestDateString = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture); 
    var StorageAccountName = "<account removed>"; 
    var StorageKey = "<key removed>"; 

    using (var client = new HttpClient()) 
    { 
     var stringToSign = new List<string>(){ 
     "GET"                        /*HTTP Verb*/ 
     ,""                         /*Content-Encoding*/ 
     ,""                         /*Content-Language*/ 
     ,""                       /*Content-Length (include value when zero)*/ 
     ,""                         /*Content-MD5*/ 
     ,""                         /*Content-Type*/ 
     ,""                         /*Date*/ 
     ,""                         /*If-Modified-Since */ 
     ,""                         /*If-Match*/ 
     ,""                         /*If-None-Match*/ 
     ,""                         /*If-Unmodified-Since*/ 
     ,""                         /*Range*/ 
     ,$"x-ms-date:{requestDateString}\nx-ms-version:2015-02-21"           /*CanonicalizedHeaders*/ 
     ,$"/{StorageAccountName}/ " + _containerName + "\ncomp:metadata\nrestype:container\ntimeout:20"  /*CanonicalizedResource*/ 
     }; 


     string signature; 
     using (var hmac = new HMACSHA256(Convert.FromBase64String(StorageKey))) 
     { 
      var compiledStringToSign = (string.Join("\n", stringToSign)); 
      byte[] dataToHmac = Encoding.UTF8.GetBytes(compiledStringToSign); 
      signature = Convert.ToBase64String(hmac.ComputeHash(dataToHmac)); 
     } 

     //Send Request 
     client.DefaultRequestHeaders.Add("x-ms-date", requestDateString); 
     client.DefaultRequestHeaders.Add("x-ms-version", " 2015-02-21"); 
     client.DefaultRequestHeaders.Add("Authorization", $"SharedKey {StorageAccountName}:" + signature); 

     var response = client.SendAsync(request); 

// 편집 요청 URL 내가 정말하지만 그것을 볼 수 없습니다, 나는 오류가 서명에 있어야합니다 생각 때문에 https://account.blob.core.windows.net/testcontainer/blobtest/blob1234

오류가 인증 실패에 대한 매우 구체적이다. 나는 그들이 일치하는지 확인하기 위해 모든 출력물을 검사했다.

+0

내가 물어 봐도 될까요? –

+0

SDK가 없는데 파이썬에서 이것을 구현했습니다. AFAIK C# SDK는 GitHub의 오픈 소스이며 코드를 검토 할 수 있습니다. 2 년 전 구현이 매우 읽기 쉽습니다. –

+0

요청 URL을 공유 할 수 있습니까? –

답변

1

블롭 내용을 얻고 싶다면, 다음 데모 코드를 사용해 보아라. 그것은 나의 편이 맞다. 당신은 C#을위한 푸른 저장 SDK를 사용하지 않는 이유

var blobStorageAccount = "account name"; 
var storageKey = "account key"; 
var containerName = "container name"; 
var requestMethod = "GET"; 
var blobName = "blob name"; // in your case:blobtest/blob1234 
var dt = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture); 
var msVersion = "2015-02-21"; 
var clientRequestId = Guid.NewGuid().ToString(); 
var canHeaders = $"x-ms-client-request-id:{clientRequestId}\nx-ms-date:{dt}\nx-ms-version:{msVersion}"; 
var canResource = $"/{blobStorageAccount}/{containerName}/{blobName}"; //not the CanonicalizedResource : /myaccount/mycontainer\ncomp:metadata\nrestype:container\ntimeout:20 
var signStr = $"{requestMethod}\n\n\n\n\n\n\n\n\n\n\n\n{canHeaders}\n{canResource}"; 
var auth = CreateAuthString(blobStorageAccount, signStr, storageKey); 
var urlPath = $"https://{blobStorageAccount}.blob.core.windows.net/{containerName}/{blobName}"; 
Uri uri = new Uri(urlPath); 
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri); 
HttpClient client = new HttpClient(); 
client.DefaultRequestHeaders.Add("x-ms-date", dt); 
client.DefaultRequestHeaders.Add("x-ms-version", msVersion); 
client.DefaultRequestHeaders.Add("x-ms-client-request-id", clientRequestId); 
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) 
{ 
    var signature = string.Empty; 
    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

+0

이 작동합니다, canonicalizedResource 변경 필요한 것입니다. Azure 설명서와 일치하지 않으므로 정보를 얻은 곳을 물어 볼 수 있습니까? – James

+0

[blob API 가져 오기] (https://docs.microsoft.com/en-us/)에 따르면 문서 문제 인 것 같습니다. rest/api/storageservices/get-blob) https://myaccount.blob.core.windows.net/mycontainer/myblob, 나는 canonicalizedResource가'$ "/ {blobStorageAccount}/{containerName}/{blobName}이어야한다고 가정합니다." '. –