-
-
Save JeremyPlease/37112e3f035ef2e9ac3d84eac5bf0c7d to your computer and use it in GitHub Desktop.
// 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__ |
@JeremyPlease Thank you!!! I was researching this for 2 days straight. Only thing I'd recommend is noting that when you switch over to this CloudFront implementation, any conditions or details you had in your IAM policy need to be implemented in the Cloud Front identity policy in the bucket permissions. Since I was using IAM with s3 it slipped me that the IAM policy was no longer in use.
Wondering also if there are any nuances to the implementation if you:
- start to use a domain name instead of the CloudFront domain.
- implement MFA on your CloudFront account
@pnutmath The aws-sdk-js-v3 is a total rewrite. I'm still using the still maintained v2 sdk in all production projects.
Confirming I've tested and am using @JeremyPlease implementation with the v3 aws-sdk successfully.
@oelbaganwg Glad to hear this was helpful! And good to know about configuring CloudFront IAM policy correctly.
• start to use a domain name instead of the CloudFront domain.
I've never tested with a non-cloudfront domain, but hypothetically it shouldn't affect anything.
• implement MFA on your CloudFront account
Also never tested this, but I think MFA should be a separate layer before the signed URL and not affect things.
Confirming I've tested and am using @JeremyPlease implementation with the v3 aws-sdk successfully.
Niiice!
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.
Fair enough