gpt4 book ai didi

c# - 服务器无法验证请求

转载 作者:行者123 更新时间:2023-12-03 01:57:09 24 4
gpt4 key购买 nike

我正在尝试使用WindowsAzure REST API在azure表中插入实体。但我收到以下 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>

以下代码创建授权 header :

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);
...
...
}

有人可以告诉我我做错了什么吗?

最佳答案

请更改以下代码行:

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)

希望这有帮助。

关于c# - 服务器无法验证请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12704575/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com