我试图让一些代码通过 C# 使用 REST API 从 S3 获取文件。我见过其他人做类似的事情,但由于某种原因,我不断收到 403 错误。我尝试使用适用于 .Net 的 AWS 开发工具包做同样的事情,它可以工作,所以我认为这是我创建授权标头的方式。
请问有人能对此有所了解吗?
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();