2013-04-05 35 views
1

所以我只是試圖列出存儲帳戶中的表以使用Query Tables方法來測試授權。我嘗試使用SDK,但SDK試圖引用RT中不可用的DLL。決定試用REST API。但我有這個天賦http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspxWindows Azure存儲的授權標題Windows Store應用程序的REST API

public async Task ExecuteAsync() 
    { 
     try 
     { 
      HttpClient client = new HttpClient(); 
      Dictionary<string, string> headers = GetHeaders("/Tables"); 
      client.DefaultRequestHeaders.Date = DateTimeOffset.Parse(headers["Date"]); 
      client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SharedKey", headers["Authorization"]); 
      const string url = "http://account-name.table.core.windows.net/Tables"; 
      XmlReader reader = XmlReader.Create(await client.GetStreamAsync(url)); 
      // 
      // Do some stuff with the reader here 
      // 
     } 
     catch (Exception e) 
     { 
      // handle exception 
     } 
    } 

    public Dictionary<string, string> GetHeaders(string resource) 
    { 
     Dictionary<string, string> headers = new Dictionary<string, string>(); 
     headers["Date"] = DateTime.Now.ToString("R"); 
     headers["Authorization"] = GetAuthorizationHeader(resource, headers["Date"]); 
     return headers; 
    } 

    public string GetAuthorizationHeader(string resource, string date) 
    { 
     const string key = PRIMARY_KEY; 
     const string accountName = ACCOUNT_NAME; 
     string signee = string.Join("\n", new List<string> { "GET", "", "", date, resource }); 
     // make the signature 
     MacAlgorithmProvider hmac = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA256"); 
     IBuffer keyMaterial = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8); 
     CryptographicKey hmacKey = hmac.CreateKey(keyMaterial); 
     IBuffer data = CryptographicBuffer.ConvertStringToBinary(signee, BinaryStringEncoding.Utf8); 
     IBuffer hash = CryptographicEngine.Sign(hmacKey, data); 
     string signature = CryptographicBuffer.EncodeToBase64String(hash); 
     return string.Format("{0}:{1}", accountName, signature); 
    } 

與認證的麻煩顯然我失去了一些東西,因爲我不斷地得到403的。通過此代碼查看任何問題?

+0

應該提到我嘗試了不同的CanonizedResources而不僅僅是/ Tables,我還嘗試了/ accountname/Tables和其他一些 – agentargo 2013-04-05 21:31:29

回答

1

幾點意見:

有適用於Windows RT的存儲客戶端庫爲好。請在這裏看看我的答案:Working with Azure in Winrt with Rest API, trouble with signature

來到你的問題,可以嘗試更改下面的代碼行:

headers["Date"] = DateTime.Now.ToString("R"); 

headers["Date"] = DateTime.UtcNow.ToString("R"); 

,看看有沒有什麼幫助。

UPDATE

我還注意到,您正在使用​​轉換Base64編碼的關鍵字節。請嘗試使用CryptographicBuffer.DecodeFromBase64Stringhttp://msdn.microsoft.com/en-us/library/windows/apps/windows.security.cryptography.cryptographicbuffer.decodefrombase64string.aspx)。

+0

UtcNow系列上的好消息。簽名仍然無效,但需要進行更改。至於使用存儲客戶端庫去,我使用.NET 4.5和一些庫的依賴關係不支持4.5,特別是System.Spatial,我爲什麼現在試圖使用REST接口 – agentargo 2013-04-08 16:19:06

+0

更新我的上面的答案。 HTH。 – 2013-04-09 02:40:48

相關問題