Create a pre-signed URL and upload the file to Google Cloud Storage using node js

I need to upload a file to Google Cloud storage using a signed URL. I need to download using different steps.

  • Create a signed url using bucketName, service key and necessary security credentials (using any node.js library)

  • Download a single file with the generated signed URL using Postman or restClient.

This is my code to create signedUrl for download

var crypto = require("crypto");
var fs = require("fs");

var URL_VALID_DURATION = 1000 * 120;//for 120 seconds

var expiry = Math.floor(((new Date).getTime() + URL_VALID_DURATION) / 1000);

var key = 'filename';
var bucketName = 'bucketName';
var accessId = 'gserviceaccount.com';
var stringPolicy = "POST\n" + "\n" + "\n" + expiry + "\n" + '/' + bucketName + '/' + key;
var base64Policy = Buffer(stringPolicy, "utf-8").toString("base64");
var privateKey = fs.readFileSync("google-services-private-key.pem", "utf8");
var signature = encodeURIComponent(crypto.createSign('sha256').update(stringPolicy).sign(privateKey, "base64"));
var signedUrl = "https://" + bucketName + ".commondatastorage.googleapis.com/" + key + "?GoogleAccessId=" + accessId + "&Expires=" + expiry + "&Signature=" + signature;

console.log(signedUrl);

But I got an error when using postman or rest with client

<?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 Google secret key and signing method.</Message>
    <StringToSign>PUT

multipart/form-data
1458024549
/bucketName/fileName</StringToSign>
</Error>
+4
source share
1 answer

stringPolicy PUT. .

var crypto = require("crypto");
var fs = require("fs");

var URL_VALID_DURATION = 1000 * 120;//for 120 seconds

var expiry = Math.floor(((new Date).getTime() + URL_VALID_DURATION) / 1000);

var key = 'filename';
var bucketName = 'bucketName';
var accessId = 'gserviceaccount.com';
var stringPolicy = "PUT\n" + "\n" + "\n" + expiry + "\n" + '/' + bucketName + '/' + key;
var base64Policy = Buffer(stringPolicy, "utf-8").toString("base64");
var privateKey = fs.readFileSync("google-services-private-key.pem", "utf8");
var signature = encodeURIComponent(crypto.createSign('sha256').update(stringPolicy).sign(privateKey, "base64"));
var signedUrl = "https://" + bucketName + ".commondatastorage.googleapis.com/" + key + "?GoogleAccessId=" + accessId + "&Expires=" + expiry + "&Signature=" + signature;

console.log(signedUrl);
+3

All Articles