C# 403禁止的错误-在c中使用Http GET请求访问AmazonS3存储桶#
我正在编写一个c代码,试图通过REST调用访问AmazonS3存储桶。 代码对s3 bucket中创建的xml文件发出get请求 我正在使用密钥和访问Id创建将在授权标头中使用的签名 我创建的签名基于亚马逊的文档, 我已经为通过身份验证的请求提供了访问s3存储桶中xml文件的权限 我使用的代码C# 403禁止的错误-在c中使用Http GET请求访问AmazonS3存储桶#,c#,rest,amazon-web-services,amazon-s3,C#,Rest,Amazon Web Services,Amazon S3,我正在编写一个c代码,试图通过REST调用访问AmazonS3存储桶。 代码对s3 bucket中创建的xml文件发出get请求 我正在使用密钥和访问Id创建将在授权标头中使用的签名 我创建的签名基于亚马逊的文档, 我已经为通过身份验证的请求提供了访问s3存储桶中xml文件的权限 我使用的代码 string AccessId = "xyz"; string SecretKey = "xyz"; string bucketName = "bucket"; string filename = "f
string AccessId = "xyz";
string SecretKey = "xyz";
string bucketName = "bucket";
string filename = "filename.xml";
string httpDate = DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss +0000\n");
string StringtoSign = "GET\n"
+ "\n"
+ "\n"
+ httpDate + "\n"
+ "/bucketName/filename.xml";
//Creating Signature
Encoding e_UTF = new UTF8Encoding();
Encoding e_ASCI = new ASCIIEncoding();
byte[] key_new= e_ASCI.GetBytes(SecretKey);
byte[] message_new = e_UTF.GetBytes(StringtoSign);
HMACSHA1 myhmacsha1 = new HMACSHA1(key_new);
byte[] final=myhmacsha1.ComputeHash(message_new);
string AWSSignature = Convert.ToBase64String(final);
// Sending request
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://"+bucketname+".s3-us-west-2.amazonaws.com/"+filename);
request.Method = "GET";
request.Headers.Add("Authorization", "AWS"+ " " + AccessId + ":" + AWSSignature);
try
{
// Getting response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
String ResStr = sr.ReadToEnd();
Console.WriteLine(ResStr);
}
catch (WebException ex)
{
var Resp = (HttpWebResponse)ex.Response;
Stream new_str=Resp.GetResponseStream();
StreamReader stred = new StreamReader(new_str);
MessageBox.Show(stred.ReadToEnd().ToString());
}
如果我将xml文件的权限设置为public,同样的代码也可以正常工作。所以它必须与签名有关。
我不确定我做错了什么。如果有人能看一下,那就太好了。您需要通过发送日期或X-Amz-date头来告诉S3您用来计算签名的日期/时间。您的代码正在对请求进行签名,就好像您正在发送日期头一样,因此您应该要求HttpWebRequest发送匹配的日期头(并确保以与HttpWebRequest相同的方式对其进行格式化):
可选地,您可能想考虑使用它,它会为您生成正确的签名。
谢谢您的建议。我能够使用此线程中提到的代码设置日期标题。我现在收到“签名不匹配”的消息以及回复。我尝试了另一种使用查询字符串身份验证的方法,并且能够正确地发送身份验证请求。但仍然无法使用授权标头发送身份验证。DateTime now = DateTime.UtcNow;
string httpDate = now.ToString("r");
...
request.Date = now;