Last active
May 28, 2024 17:42
-
-
Save JeremyPlease/37112e3f035ef2e9ac3d84eac5bf0c7d to your computer and use it in GitHub Desktop.
Sign a CloudFront URL with NodeJS AWS SDK https://medium.com/roam-and-wander/using-cloudfront-signed-urls-to-serve-private-s3-content-e7c63ee271db
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// load the AWS SDK | |
const AWS = require('aws-sdk') | |
// load CloudFront key pair from environment variables | |
// Important: when storing your CloudFront private key as an environment variable string, | |
// you'll need to replace all line breaks with \n, like this: | |
// CF_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nMIIE...1Ar\nwLW...2eL\nFOu...k2E\n-----END RSA PRIVATE KEY-----" | |
const cloudfrontAccessKeyId = process.env.CF_ACCESS_KEY_ID | |
const cloudFrontPrivateKey = process.env.CF_PRIVATE_KEY | |
const signer = new AWS.CloudFront.Signer(cloudfrontAccessKeyId, cloudFrontPrivateKey) | |
// 2 days as milliseconds to use for link expiration | |
const twoDays = 2*24*60*60*1000 | |
// sign a CloudFront URL that expires 2 days from now | |
const signedUrl = signer.getSignedUrl({ | |
url: 'https://248hf0w8hs.cloudfront.net/secret-image.jpg', | |
expires: Math.floor((Date.now() + twoDays)/1000), // Unix UTC timestamp for now + 2 days | |
}) | |
// signedUrl is now a signed CloudFront URL: | |
// https://248hf0w8hs.cloudfront.net/secret-image.jpg?Expires=1531165045&Key-Pair-Id=HDIWEUY39S87XHCJDJUQODJ20AL&Signature=0SGI2...K2JHID__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this saved us thank you!. we're are on aws-sdk v3 and no issues to report, the code is returning a signedUrl successfully. I might add, I also had to wrap in double quotes, in single quotes the function returns an error. Very fussy indeed.