【发布时间】:2017-02-15 04:39:57
【问题描述】:
我正在尝试使用 fetch 将文件(通过 FormData)POST 上传到 S3 存储桶。
我正在使用aws4-signature 创建策略签名。
我使用"Creating a POST policy" 和"Browser-Based Uploads Using POST" 作为指南。
签名
我 100% 知道我的 ACCESS_KEY 和 SECRET 是正确的。
下面创建的date 与x-amz-date 和x-amz-credential 使用的相同。
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>
【问题讨论】:
标签: javascript node.js amazon-web-services amazon-s3