1

我正在尝试WindowsAzure REST API用于在天蓝色表中插入实体。但我得到以下 WebException :

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
 <error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
  <code>AuthenticationFailed</code>
  <message xml:lang="en-US">
                            Server failed to authenticate the request. Make sure the 
                            value of Authorization header is formed correctly including 
                            the signature.
                            RequestId:bbcf614e-6a12-4fb0-be68-16246853111d
                            Time:2012-10-03T08:21:46.3010154Z
  </message>
 </error>

以下代码创建授权标头:

private String CreateAuthorizationHeader(String canonicalizedString)
{
    String signature = string.Empty;
    using (HMACSHA256 hmacSha256 = new HMACSHA256(Encoding.UTF8.GetBytes(AzureStorageConstants.Key)))
    {
        Byte[] dataToHmac = Encoding.UTF8.GetBytes(canonicalizedString);
        signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
    }

    String authorizationHeader = String.Format(
          CultureInfo.InvariantCulture,
          "{0} {1}:{2}",
          AzureStorageConstants.SharedKeyAuthorizationScheme,
          AzureStorageConstants.Account,
          signature);

    return authorizationHeader;
}

生成规范化字符串的代码

   public void InsertEntity(string tablename, string artist, string title)
   {
    string requestmethod = "POST";
    string urlpath = tablename;
    string storageserviceversion = "2009-09-19";
    string dateinrfc1123format = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
    string contentmd5 = string.Empty;
    string contenttype = "application/atom+xml";
    String canonicalizedresource = string.Format("/{0}/{1}", AzureStorageConstants.Account, urlpath);
    String stringtosign = String.Format(
      "{0}\n{1}\n{2}\n{3}\n{4}",
      requestmethod,
      contentmd5,
      contenttype,
      dateinrfc1123format,
      canonicalizedresource);

    String authorizationHeader = CreateAuthorizationHeader(stringtosign);
    ...
    ...
   }

谁能告诉我我做错了什么?

4

1 回答 1

2

请更改以下代码行:

using (HMACSHA256 hmacSha256 = new HMACSHA256(Encoding.UTF8.GetBytes(AzureStorageConstants.Key)))
{
    Byte[] dataToHmac = Encoding.UTF8.GetBytes(canonicalizedString);
    signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
}

using (HMACSHA256 hmacSha256 = new HMACSHA256(Convert.FromBase64String(AzureStorageConstants.Key)))
{
    Byte[] dataToHmac = Encoding.UTF8.GetBytes(canonicalizedString);
    signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
}

基本上您的代码失败了,因为您使用的是 Encoding.UTF8.GetBytes(accountKey)。我们需要使用 Convert.FromBase64String(accountKey)

希望这可以帮助。

于 2012-10-03T11:46:26.527 回答