c# - Amazon S3 REST API 403 错误 c#

标签 c# rest amazon-s3

我试图让一些代码通过 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/

相关文章:

c# - 如何在文本框中显示换行命令?

java - 如何使用 JAX-RS 和 Jersey 处理 CORS

java - 限制 REST 中的 json 参数

typescript - 如何检查角度 8 中的响应或状态代码以将文件上传到 S3 预签名 URL 且状态代码为 200

amazon-web-services - AWS S3 - 能够从本地上传文件但不能从部署(拒绝访问)

C# 特化泛型类

c# - 从内存运行 exe 时出现 "Parameter count mismatch"

python - 匹配 s3 链接的正则表达式

c# - 更改 SSL 网站的 Web.Config

java - Java 桌面应用程序中的 RESTful Web 服务