简体   繁体   English

预签名 PUT 从 PostMan 起有效,但 403 Forbidden 从 C# HttpClient

[英]Presigned PUT works from PostMan, but 403 Forbidden from C# HttpClient

I have generated a pre-signed url from S3 using the following.Net code (in a service that has the appropriate IAM role/permission for the bucket)我已经使用以下 .Net 代码从 S3 生成了预签名的 url(在具有适当的 IAM 角色/存储桶权限的服务中)

            var key = GenerateKey(jobId, batchId);
            var linkExpiresAt = _dateTimeService.Now().AddMinutes(_expiryTime);

            var request = new GetPreSignedUrlRequest
            {
                BucketName = _bucketName,
                Key = key,
                Verb = HttpVerb.PUT,
                ContentType = "application/json",
                Expires = linkExpiresAt,
                ServerSideEncryptionMethod = ServerSideEncryptionMethod.None
            };

            var url = _s3Client.GetPreSignedURL(request);

I can use this url in Postman to do a PUT with content 'JSON', but when I try to use it from code, I get 403我可以在 Postman 中使用这个 url 来执行内容为“JSON”的 PUT,但是当我尝试从代码中使用它时,我得到 403

            var content = new StringContent(mooStr, Encoding.ASCII, "application/json");
            var fileStreamResponse = await httpClient.PutAsync(
                url,
                content);

Is there anything that stands out as wrong with the.Net attempt to PUT to the url? .Net 尝试 PUT 到 url 有什么明显的错误吗?

If anyone comes across the same issue, I found the solution.如果有人遇到同样的问题,我找到了解决方案。

When I ran Fiddler, I captured the successful request from Postman and the failing request from .Net code.当我运行 Fiddler 时,我捕获了来自 Postman 的成功请求和来自 .Net 代码的失败请求。 The only difference I could spot was that the successful one had this header (I'd changed to text/plain since my first post, but the problem remained):-我能发现的唯一区别是成功的有这个标题(自从我第一次发帖以来,我已经改为 text/plain,但问题仍然存在):-

Content-Type: text/plain内容类型:文本/纯文本

and the failing one from .Net had:-来自.Net的失败者有:-

Content-Type: text/plain;内容类型:文本/纯文本; charset=utf-8字符集=utf-8

A bit of a search around StackOverflow found me these posts对 StackOverflow 的一些搜索找到了我这些帖子

How to remove charset=utf8 from Content-Type header generated by HttpClient.PostAsJsonAsync()? 如何从 HttpClient.PostAsJsonAsync() 生成的 Content-Type 标头中删除 charset=utf8?

How do I not exclude charset in Content-Type when using HttpClient? 使用 HttpClient 时如何不排除 Content-Type 中的字符集?

I edited the captured request in Fiddler and removed the charset and it worked.我在 Fiddler 中编辑了捕获的请求并删除了字符集并且它起作用了。 Altering my original code to the following worked (note - setting text/plain on the StringContent didn't work):-将我的原始代码更改为以下有效(注意 - 在 StringContent 上设置 text/plain 不起作用):-

            var content = new StringContent(mooStr);
            content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/plain");

            var fileStreamResponse = await httpClient.PutAsync(
                Url,
                content); 

Following code worked for me (for posting a file of type IFormFile):以下代码对我有用(用于发布 IFormFile 类型的文件):

public async Task<bool> UploadObject(string preSignedUrl)
{
    try
    {
        using (var client = new HttpClient())
        {
            StreamContent streamContent = new StreamContent(file.OpenReadStream());
            var result = await client.PutAsync(preSignedUrl, streamContent);
            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception();
            }
         }

          return true;
     }
     catch (Exception e)
     {
         .... 
     }

     return false;
}

Create the preSignedUrl with the IAmazonS3 package.使用 IAmazonS3 package 创建 preSignedUrl。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Aws sam cognito api 网关 - 禁止访问令牌,但如果它来自 postman,则可以使用 - Aws sam cognito api gateway - access token forbidden but works if it's from postman 测试 AWS S3 Presigned Url 返回 403 Forbidden (Nodejs) - Testing a AWS S3 Presigned Url returns 403 Forbidden (Nodejs) Firebase 云 Function 适用于 Postman 但不适用于 App - Firebase Cloud Function Works With Postman But Not From App 尝试从 Firebase 存储加载图像时出现 403 禁止错误 - Getting 403 Forbidden error when trying to load image from Firebase Storage 403 禁止。 从 s3 通过云端服务多页应用程序时 - 403 Forbidden. when serving multipage app via cloudfront from s3 来自 API 网关的 502 错误响应反应但在 postman 上工作 - 502 error response from API Gateway in react but works on postman 从前端上传视频到预签名的 URL - Uploading a video to the presigned URL from Frontend 无法从 S3 下载文件,因为“调用 HeadObject 操作时发生客户端错误 (403):禁止访问” - Unable to download file from S3 because "A client error (403) occurred when calling the HeadObject operation: Forbidden" 无法获取“*/maven-metadata.xml”。 从服务器收到状态代码 403:发布到 AWS CodeArtifact 时被禁止 - Could not GET '*/maven-metadata.xml'. Received status code 403 from server: Forbidden while publishing to AWS CodeArtifact 使用预签名 URL 将文件放入 S3 - PUT file to S3 with presigned URL
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM