我正在尝试为Google Cloud Storage中的私有(private)存储文件创建签名;这样我就可以发布一个限时链接。

目前正在这样做,并且签名太短了……我要去哪里错了?

var crypto = require("crypto");

var ttl = new Date().getTime() + 3600;
var id = 'the_target_file.txt';
var bucketName = 'bucket_name';
var POLICY_JSON = "GET\n" + "\n" + "\n" + ttl + "\n" + '/' + bucketName + '/' + id;

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

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

console.log ( signature );

最佳答案

现在有一个用于获取签名URL的API/模块。
模块:https://www.npmjs.com/package/@google-cloud/storage
API文档:https://cloud.google.com/nodejs/docs/reference/storage/1.6.x/File#getSignedUrl
例子

var storage = require('@google-cloud/storage')();
var myBucket = storage.bucket('my-bucket');

var file = myBucket.file('my-file');

//-
// Generate a URL that allows temporary access to download your file.
//-
var request = require('request');

var config = {
  action: 'read',
  expires: '03-17-2025'  // this could also include time (MM-DD-YYYYTHH:MM:SSZ)
};

file.getSignedUrl(config, function(err, url) {
  if (err) {
    console.error(err);
    return;
  }

  // The file is now available to read from this URL.
  request(url, function(err, resp) {
    // resp.statusCode = 200
  });
});

关于node.js - 使用NodeJS为Google Cloud Storage创建签名的URL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20754279/

10-17 02:50