Forked from JeremyPlease/signed-cloudfront-url.js
Last active
January 7, 2020 16:54
-
-
Save natac13/1a5f23c3ffcaca543f3697d55d51f0eb 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