AWS S3基于浏览器的上传使用POST(AWS4)和fetch

时间:2017-01-19 17:35:23

标签: javascript node.js amazon-web-services amazon-s3

我正在尝试使用fetch POST文件(通过FormData)上传到S3存储桶。

我正在使用aws4-signature来创建政策签名。

我正在使用"Creating a POST policy""Browser-Based Uploads Using POST"作为指南。

特征

我100%知道我的ACCESS_KEYSECRET是正确的。

下面创建的date与用于x-amz-datex-amz-credential的{​​{1}}相同。

const aws4_sign = require("aws4-signature");

const date = new Date();
const signature = aws4_sign(SECRET, date, "us-west-2", "s3", BASE64_POLICY);

HTTPS请求

const url = "https://s3-us-west-2.amazonaws.com/example-bucket";

const data = {
  "AWSAccessKeyId": "ACCESS_KEY",
  "key": "photos/7bf0b615-badc-4f57-8320-71f7e690554e.png",
  "acl": "public-read",
  "policy": "BASE64_POLICY",
  "signature": "POLICY_SIGNATURE",
  "content-type": "image/png",
  "x-amz-algorithm": "AWS4-HMAC-SHA256",
  "x-amz-credential": "ACCESS_KEY/20170119/us-west-2/s3/aws4_request",
  "x-amz-date": "20170119T165423Z",
};

const policy = JSON.parse(window.atob(data.policy));
// {
//   "expiration": "2017-01-19T17:24:23.090Z",
//   "conditions": [
//     { "key": "photos/7bf0b615-badc-4f57-8320-71f7e690554e.png" },
//     { "bucket": "example-bucket" },
//     { "acl": "public-read" },
//     [ "starts-with", "$Content-Type", "image/png" ],
//     [ "starts-with", "$Content-Length", "" ],
//     [ "content-length-range", 1, 10000000 ],
//     { "x-amz-algorithm": "AWS4-HMAC-SHA256" },
//     { "x-amz-server-side-algorithm": "AES256" },
//     { "x-amz-storage-class": "STANDARD" },
//     { "x-amz-date": "20170119T165423Z" },
//     { "x-amz-credential": "ACCESS_KEY/20170119/us-west-2/s3/aws4_request" }
//   ]
// }

const body = new FormData();
for (const key in data) {
  body.append(key, data[key]);
}

const promise = fetch(url, {method: 'POST', body});

XML响应

<?xml version="1.0" encoding="UTF-8"?>
<Error>
  <Code>SignatureDoesNotMatch</Code>
  <Message>The request signature we calculated does not match the signature you provided.
    Check your key and signing method.</Message>
  <AWSAccessKeyId>ACCESS_KEY</AWSAccessKeyId>
  <StringToSign>BASE64_POLICY</StringToSign>
  <SignatureProvided>POLICY_SIGNATURE</SignatureProvided>
  <StringToSignBytes>65 79 4a 6c 65 48 42 70 63 6d 46 30 61 57 39 75 49 6a 6f 69 4d 6a ... </StringToSignBytes>
  <RequestId>C0AE9240D8991EEF</RequestId>
  <HostId>Zih68OHYod6c3HX8ecVNXCU1Iz/ek0UGEh9Xwb5TBNlS7IQUZjdofNRqk/Kl9Rdq3rNkRhNxj9s=</HostId>
</Error>

1 个答案:

答案 0 :(得分:0)

尝试删除

  

“AWSAccessKeyId”:“ACCESS_KEY”,

根据此处的文档 http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html

没有AWSAccessKeyId 签名v4。

AWSAccessKeyId用于签名v2。

提供它将导致s3认为您正在使用签名v2。 而且没有X-Amz-Credential 在签名v2。