我试图让一些代码通过 C# 使用 REST API 从 S3 获取文件。我见过其他人做类似的事情,但出于某种原因,我一直收到 403 错误。我已经尝试使用适用于 .Net 的 AWS SDK 来做同样的事情并且它有效,所以我假设这是我创建授权 header 的方式。
请问有人能解释一下吗?
string awsAccessId = "***";
string awsSecretKey = "***";
string bucketName = "thebucket";
string httpDate = DateTime.Now.ToString("ddd, dd MMM yyyy HH:mm:ss +0000\n");
string canonicalString = "GET\n"
+ "\n"
+ "\n"
+ "x-amz-date:" + httpDate + "\n"
+ "/" + bucketName + "/readme.txt";
// now encode the canonical string
Encoding ae = new UTF8Encoding();
// create a hashing object
HMACSHA1 signature = new HMACSHA1();
// secretId is the hash key
signature.Key = ae.GetBytes(awsSecretKey);
byte[] bytes = ae.GetBytes(canonicalString);
byte[] moreBytes = signature.ComputeHash(bytes);
// convert the hash byte array into a base64 encoding
string encodedCanonical = Convert.ToBase64String(moreBytes);
// Send the request
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://" + bucketName +".s3.amazonaws.com/readme.txt");
request.Headers.Add("x-amz-date", httpDate);
request.Headers.Add("Authorization", "AWS " + awsAccessId + ":" + encodedCanonical);
request.Method = "GET";
// Get the response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(response.StatusCode);
Console.Read();
最佳答案
我测试了你的代码,它有效!您只需要一个额外的\n 加上将 http 更改为 https 就可以了。
string stringToConvert = "GET\n"
+ "\n"
+ "\n"
+ "\n"
+ "x-amz-date:" + timeStamp + "\n"
+ "/" + bucketName + "/" + FileName;
Amazon Rest API 没有很好的文档,缺乏示例让每个人都转而使用 SDK。
关于c# - Amazon S3 REST API 403 错误 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19689484/