我正在尝试按照 AWS 文档签署 AWS 请求中给出的示例并在 C# 中进行 ListUsers 调用。我已经到了生成签名的最后阶段(即准备提交在签名 4 请求示例中给出的签名请求)。但是我在下面粘贴的代码在提交时会抛出“错误请求”异常。
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);