我正在尝试按照AWS文档Signing AWS requests中给出的示例,并在C#中进行ListUsers调用。我已经到达生成签名的最后阶段(即准备提交signature-4 request examples处给出的签名请求)。但我下面粘贴的代码在提交时会抛出“错误请求”异常。
static void submitSignedRequest(string my_access_key, string my_secret_key, string signature, string curr_utc_date_string, string curr_utc_datetime_string)
{
string url = "https://iam.amazonaws.com/?Action=ListUsers&Version=2010-05-08&X-Amz-Algorithm=AWS4-HMAC-SHA256&" +
"X-Amz-Credential=" + my_access_key + "/" + curr_utc_date_string + "/us-east-1/iam/aws4_request&X-Amz-Date=" + curr_utc_datetime_string +
"&X-Amz-SignedHeaders=content-type;host;x-amz-date&X-Amz-Signature=" + signature;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.Host = "iam.amazonaws.com";
request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
WebHeaderCollection headers = (request as HttpWebRequest).Headers;
headers.Add("Authorization", "AWS4-HMAC-SHA256 Credential=" + my_access_key +"/" + curr_utc_date_string + "/us-east-1/iam/aws4_request, " +
"SignedHeaders=content-type;host;x-amz-date, Signature=" + signature);
headers.Add("x-amz-date", curr_utc_datetime_string);
HttpWebResponse response;
try
{
response = request.GetResponse() as HttpWebResponse;
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
}
}
我得到的输出是:
Error Message: The remote server returned an error: (400) Bad Request.
有人可以帮助我在这里做错了吗?
编辑:
我终于自己解决了这个问题。我不得不把它变成下面的。 (答案是针对RDS的,但我相信可以看出差异是什么)。string url = "https://rds.us-west-1.amazonaws.com";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
// ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "Action=DescribeDBInstances&Version=2013-09-09";
byte[] data = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.Host = "rds.us-west-1.amazonaws.com";
request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
// request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
WebHeaderCollection headers = (request as HttpWebRequest).Headers;
request.Headers.Add("Authorization", "AWS4-HMAC-SHA256 Credential=" + my_access_key + "/" + curr_utc_date_string + "/us-west-1/rds/aws4_request, " +
"SignedHeaders=content-type;host;x-amz-date, Signature=" + signature);
request.Headers.Add("x-amz-date", curr_utc_datetime_string);
答案 0 :(得分:4)
有人可以帮助我在这里做错了吗?
也许,但我强烈建议您一起跳过这一努力,而只是使用优秀的AWS SDK for .NET代替所有AWS API交互,因为它确实通过提供.NET帮助消除编码的复杂性适用于许多AWS服务的API,包括Amazon S3,Amazon EC2,DynamoDB等等。
但如果你真的需要或想要自己动手,我建议你只看一下这些SDK的源代码,这些代码都是available at GitHub,包括AWS SDK for .NET的代码。 - 关于手头的问题,您可能希望开始研究AWS4Signer.cs。