我正在尝试使用WindowsAzure REST API
在azure表中插入Entity。但我得到以下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;
}
生成canonicalizedString的代码
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);
...
...
}
有人可以告诉我我做错了吗?
答案 0 :(得分: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)
希望这有帮助。