Amazon S3 POST api, and signing a policy with NodeJS

后端 未结 4 1296
轮回少年
轮回少年 2020-12-24 03:08

I\'m trying to get an built that allows users to upload a file directly to my Amazon S3 bucket, from a NodeJS powered website. It seems the only tutorials out there, other t

4条回答
  •  一生所求
    2020-12-24 03:21

    Ok, I finally figured it out. After playing the random guessing game for a VERY long time, I thought to myself

    "maybe i need to sign the base64 encoded policy" - me

    and BAM that was it.

    I also re-ordered the conditions to match how the form is posting, though I'm not sure this makes a difference.

    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);
    };
    

    Hopefully this will help others that run in to the same problem.

提交回复
热议问题