nodejs-docs-samples
nodejs-docs-samples copied to clipboard
Support creating signed urls for Cloud CDN
Originally filed in nodejs-storage by @TriPSs This is a request for a Node.js sample on this page
Is your feature request related to a problem? Please describe. We want to implement signed urls that go through the load balancer with Cloud CDN, this library does not yet expose a method that can be used to generate those urls.
Describe the solution you'd like An method that will generate these urls for us.
Describe alternatives you've considered Create the custom code inside the application itself.
Additional context Would be awesome if this could be integrated inside the library as now everyone who needs this needs to figure it out themselves (As the Google Cloud docs does not have an example for node) and create their own solution.
Outstanding question:
if I understood it correctly you need to create a custom "URL signing key" for the load balancer and use that one when creating the signed url so Cloud CDN / Load Balancer can accept it. Or is this incorrect?
I was going through Cloud CDN documentation to find how to programmatically generate signed CDN urls and nodejs example was really missing for me. After several hours of trial and error I managed to came up with a solution. I opened a PR adding corresponding nodejs code snippet https://github.com/GoogleCloudPlatform/nodejs-docs-samples/pull/4011.
Not sure what is the process of updating above mentioned docs to add this snippet though.
For anybody searching online for a quick copy-paste, here is the whole snippet:
const crypto = require('crypto');
/**
* Sign url to access Google Cloud CDN resource secured by key.
* @param url the Cloud CDN endpoint to sign
* @param keyName name of the signing key configured in the backend service/bucket
* @param keyValue value of the signing key
* @param expirationDate the date that the signed URL expires
* @return signed CDN URL
*/
function signUrl(url, keyName, keyValue, expirationDate) {
const urlObject = new URL(url);
urlObject.searchParams.set(
'Expires',
Math.floor(expirationDate.valueOf() / 1000).toString()
);
urlObject.searchParams.set('KeyName', keyName);
const signature = crypto
.createHmac('sha1', Buffer.from(keyValue, 'base64'))
.update(urlObject.href)
.digest('base64url');
urlObject.searchParams.set('Signature', signature);
return urlObject.href;
}