4
votes

i need to upload file to google cloud storage using signed url. i need to upload by diffrent steps.

  1. Create a signedUrl using bucketName, service key and needed security credentials.(using any node.js library)

  2. upload a single file with created signed url using a Postman or restClient.

This is my code for creating signedUrl for uploading

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 error, when using with postman or rest 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>
1

1 Answers

3
votes

Just changed stringPolicy method to PUT. and also send image as binary.

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