。NET中使用Rest Sharp向Amazon发送请求

问题描述 投票:1回答:1

因此,我试图通过UPC称为搜索项的方法向亚马逊的API发出请求。到目前为止,我在这里所做的工作如下:

   var client = new RestClient("http://webservices.amazon.com/onca/xml");
    string itemid = "694318020913";
    var timestamp = DateTime.UtcNow.ToString("o");
     var signature = getSignatureKey("some key here", timestamp, "east-us-1", "iam");
     var request = new RestRequest(Method.POST);
     request.AddParameter("application/x-www-form-urlencoded", "Service=AWSECommerceService&Operation=ItemLookup&ResponseGroup=Large&SearchIndex=All&IdType=UPC&ItemId="+itemid+"&AWSAccessKeyId=accesssKey&AssociateTag=associateTag&Timestamp=" + timestamp + "&Signature=" + signature, ParameterType.RequestBody);
     var res = client.Execute(request).Content;

这些是我在亚马逊文档中找到的应该用来计算签名的辅助方法:

  static byte[] HmacSHA256(String data, byte[] key)
        {
            string algorithm = "HmacSHA256";
            KeyedHashAlgorithm kha = KeyedHashAlgorithm.Create(algorithm);
            kha.Key = key;

            return kha.ComputeHash(Encoding.UTF8.GetBytes(data));
        }

        static byte[] getSignatureKey(string key, string dateStamp, string regionName, string serviceName)
        {
            byte[] kSecret = Encoding.UTF8.GetBytes(("AWS4" + key).ToCharArray());
            byte[] kDate = HmacSHA256(dateStamp, kSecret);
            byte[] kRegion = HmacSHA256(regionName, kDate);
            byte[] kService = HmacSHA256(serviceName, kRegion);
            byte[] kSigning = HmacSHA256("aws4_request", kService);

            return kSigning;
        }

现在让我感到困惑的是,我从亚马逊收到以下消息:

The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details c# .net

我的问题是:

  1. 在此getSignatureKey方法中,实际上我必须传递哪个密钥?

    • 我有几个来自亚马逊的钥匙,它们是:
    • 访问密钥,秘密密钥,关联密钥?

我在这里做错了什么?有人可以帮我吗?

c# asp.net asp.net-mvc amazon-web-services amazon-s3
1个回答
0
投票

抱歉这三年的痛苦,但对未来的读者:

更改此行:

var signature = getSignatureKey;

收件人:

var signatureKey = getSignatureKey;

现在您意识到我们使用的是signatureKey,而不是原始密钥。

删除“ &Signature=' + signature”,并使用signatureKey对正在作为请求参数添加的字符串进行签名(URL首先对名称和值进行编码,保留=和&未编码)。 -时间戳可能是唯一需要url编码的部分。然后对刚刚创建的签名字符串进行url编码,并将其添加到原始未签名字符串的末尾。现在,使用AddParameter将新字符串添加到请求中。

如果再次出现“不匹配”错误,请使用您自己的使用System.Net.HttpWebRequest的代码替换RestSharp,以消除可能的问题。弄清楚如何使用HttpWebRequest不会使此任务变得更加困难。

© www.soinside.com 2019 - 2024. All rights reserved.