21

我正在尝试构建一个允许用户从 NodeJS 支持的网站将文件直接上传到我的 Amazon S3 存储桶的构建。除了实际的亚马逊文档之外,似乎唯一的教程都已经过时了。

我一直在关注本教程,以获取基本信息,但它又过时了。它没有要crypto更正的方法调用,因为它尝试将原始 JavaScript 对象传递给该update方法,这会引发错误,因为它不是字符串或缓冲区。

我也一直在查看knox npm 包的源代码。它没有内置 POST 支持 - 我完全理解,因为一旦它具有正确的字段,它就是浏览器在执行 POST。诺克斯似乎确实有正确的代码来签署政策,我试图让我的代码在此基础上工作......但再次无济于事。

这是我想出的代码。它产生一个base64编码的策略,并创建一个签名......但根据亚马逊的说法,当我尝试上传文件时,它是错误的签名。


var crypto = require("crypto");
var config = require("../../amazonConfig.json");

exports.createS3Policy = function(callback) {
  var date = new Date();

  var s3Policy = {
    "expiration": "2014-12-01T12:00:00.000Z",
    "conditions": [
      {"acl": "public-read"}, 
      ["content-length-range", 0, 2147483648],
      {"bucket": "signalleaf"}, 
      ["starts-with", "$Cache-Control", ""],
      ["starts-with", "$Content-Type", ""],
      ["starts-with", "$Content-Disposition", ""],
      ["starts-with", "$Content-Encoding", ""],
      ["starts-with", "$Expires", ""],
      ["starts-with", "$key", "/myfolder/"], 
      {"success_action_redirect": "http://example.com/uploadsuccess"},
    ]
  };

  var stringPolicy = JSON.stringify(s3Policy).toString("utf-8");
  var buffer = Buffer(stringPolicy, "utf-8");

  var encoded = buffer.toString("base64");
  var signature = crypto.createHmac("sha1", config.secretKey)
    .update(new Buffer(stringPolicy, "utf-8")).digest("base64");


  var s3Credentials = {
    s3PolicyBase64: encoded,
    s3Signature: signature
  };

  GLOBAL.s3creds = s3Credentials;

  callback(s3Credentials);
};

我显然做错了什么,在这里。但我不知道是什么。谁能帮助确定我做错了什么?我的问题在哪里?有没有人有关于如何从 NodeJS v0.10.x 生成带有签名的正确 Amazon S3 策略的工作教程,用于 POST 到 s3 REST api?

4

4 回答 4

36

好的,我终于想通了。在玩了很长时间的随机猜谜游戏后,我心想

“也许我需要签署 base64 编码策略” - 我

BAM就是这样。

我还重新排序了条件以匹配表单的发布方式,但我不确定这会有所不同。

var crypto = require("crypto");
var config = require("../../amazonConfig.json");

exports.createS3Policy = function(contentType, callback) {
  var date = new Date();

  var s3Policy = {
    "expiration": "2014-12-01T12:00:00.000Z", // hard coded for testing
    "conditions": [
      ["starts-with", "$key", "somefolder/"], 
      {"bucket": "my-bucket-name"}, 
      {"acl": "public-read"}, 
      ["starts-with", "$Content-Type", contentType],
      {"success_action_redirect": "http://example.com/uploadsuccess"},
    ]
  };

  // stringify and encode the policy
  var stringPolicy = JSON.stringify(s3Policy);
  var base64Policy = Buffer(stringPolicy, "utf-8").toString("base64");

  // sign the base64 encoded policy
  var signature = crypto.createHmac("sha1", config.secretKey)
    .update(new Buffer(base64Policy, "utf-8")).digest("base64");

  // build the results object
  var s3Credentials = {
    s3Policy: base64Policy,
    s3Signature: signature
  };

  // send it back
  callback(s3Credentials);
};

希望这将帮助遇到同样问题的其他人。

于 2013-08-28T02:03:11.333 回答
19

我修改了前面的一些例子,因为它对我不起作用:亚马逊返回了一个关于签名损坏的错误。

以下是使用 POST(AWS 签名版本 4)为基于浏览器的上传创建签名的方法

http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-authentication-HTTPPOST.html

计算签名

var CryptoJS = require("crypto-js");

var accessKeyID = "PUT YOUR DATA";
var secretAccessKey = "PUT YOUR DATA";

var bucket = "PUT YOUR BUCKET NAME";
var region = "eu-central-1"; // overwrite with your region
var folder = "users/"; // overwrite with your folder
var expiration = "2015-09-28T12:00:00.000Z"; // overwrite date
var date = "20150927"; // overwrite date
var serviceName = "s3";


function getSignatureKey(key, dateStamp, regionName, serviceName) {
   var kDate = CryptoJS.HmacSHA256(dateStamp, "AWS4" + key);
   var kRegion = CryptoJS.HmacSHA256(regionName, kDate);
   var kService = CryptoJS.HmacSHA256(serviceName, kRegion);
   var kSigning = CryptoJS.HmacSHA256("aws4_request", kService);

   return kSigning;
}

var s3Policy = {"expiration": expiration,
  "conditions": [
   {"bucket": bucket},
   ["starts-with", "$key", folder],
   {"acl": "public-read"},
   ["starts-with", "$Content-Type", "image/"],
   {"x-amz-meta-uuid": "14365123651274"},
   ["starts-with", "$x-amz-meta-tag", ""],
   {"x-amz-credential": accessKeyID + "/" + date + "/" + region + "/" + serviceName +"/aws4_request"},
   {"x-amz-algorithm": "AWS4-HMAC-SHA256"},
   {"x-amz-date": date + "T000000Z" }
  ]
};

var base64Policy = new Buffer(JSON.stringify(s3Policy), "utf-8").toString("base64");
console.log('base64Policy:', base64Policy);

var signatureKey = getSignatureKey(secretAccessKey, date, region, serviceName);
var s3Signature = CryptoJS.HmacSHA256(base64Policy, signatureKey).toString(CryptoJS.enc.Hex);
console.log('s3Signature:', s3Signature);

接下来生成的 base64Policy 和 s3Signature 我在表单中用于上传。示例在这里: http ://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html

非常重要的是检查您在 html 表单和策略中是否具有相同的字段和值。

于 2015-09-26T08:49:46.767 回答
2

我仍然遇到问题,所以我解决了这些问题并在此处发布了我的解决方案:

https://github.com/nikkwong/ng2-s3-uploader

简而言之,如果您在构建签名时使用 scabbiaza 的答案,请确保像这样构建表单:

let formData = new FormData;
formData.append('acl', xAmzAcl);
formData.append('Content-Type', file.type);
formData.append('X-Amz-Date', xAmzDate);
formData.append('x-amz-server-side-encryption', xAmzServerSideEncryption);
formData.append('x-amz-meta-uuid', xAmzMetaUuid);
formData.append('X-Amz-Algorithm', xAmzAlgorithm);
formData.append('X-Amz-Credential', xAmzCredential);
formData.append('X-Amz-Signature', s3Signature);
formData.append('Policy', base64Policy);
formData.append('key', folder + '/' + file.name);
// File field must come last! 
formData.append('file', file);
于 2016-05-12T08:22:01.600 回答
1

AWS 开发工具包现在提供了一种使用createPresignedPost().

文档:https ://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#createPresignedPost-property

于 2020-05-25T08:23:52.453 回答