Amazon S3 无法通过 Cloudfront 上传文件

Amazon S3 can not upload file via Cloudfront

我想通过 Cloudfront 将带有签名 URL 的文件上传到 S3。 Cloudfront 行为中允许使用 HTTP PUT。 存储桶策略

             {
        "Sid": "2",
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E1C2T5UJU07REZ"
        },
        "Action": [
            "s3:PutObject",
            "s3:PutObjectAcl",
            "s3:GetObject"
        ],
        "Resource": "arn:aws:s3:::testback/*"
    }

在 CORS 配置中允许 HTTP PUT。 Cloudfront 用户也有读、写权限。 当我尝试上传带有签名 URL.

的文件时
curl -v -X PUT -F file=@hello.txt  http://my-host.cloudfront.net/hello.txt?Expires=1514764800&Signature=MySig&Key-Pair-Id=My-KeyPair

我有一个错误:

InvalidRequestThe authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256. 5D5DEF3D06F4583C8rBCpTUzYwm1ccc8IfkNtUnkuLxr3RZ2n7xn1j+VvP5dpG+3NMpHKPiNQ5tKpJjVliZ9UBI52vk=

日志:

2017-06-19 03:23:08 FRA54 726 My-IP PUT
my-host.cloudfront.net /hello.txt 400 -
curl/7.50.1
Expires=1514764800&Signature=My-Sig&Key-Pair-Id=My-KeyPair - Error MMHwKFzGuBzrlgP0yV71elcwEp2RVBAwJRJD1A5rO4Na6UmeKvcZPQ==
my-host.cloudfront.net http 838 0.235 - --
Error HTTP/1.1

此外,GET、DELETE 工作正常。

来自 CloudFront 文档:

If you're using an origin access identity and if your bucket is in one of the regions that requires signature version 4 for authentication, note the following:

DELETE, GET, HEAD, OPTIONS, and PATCH requests are supported without qualifications.

If you want to submit PUT requests to CloudFront to upload objects to your Amazon S3 bucket, you must add an x-amz-content-sha256 header to the request, and the header value must contain a SHA256 hash of the body of the request.

http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html#private-content-origin-access-identity-signature-version-4

您需要在 x-amz-content-sha256 请求 header.

中添加 object body 的 SHA256 的十六进制表示

CloudFront 将 header 包含在 PUT 中作为内部切换到 V4 签名算法的神奇触发器,这似乎出乎意料......但由于上传是强制性的,如果没有它,V4 签名将无效,所以它甚至可能不会尝试 V4(CloudFront pre-dates Signature V4)。对于其他操作,V4 不需要修改 user-agent 行为,但对于 PUT,CloudFront 在没有 V2 的情况下默认使用 V2 是有意义的,即使这是错误的,这样现有代码就不会在它已经工作的地方中断。无论如何,这似乎应该是您的解决方案。