DEV Community

AWS CloudFront — Secure URL Methods of Generation


AWS CloudFront sign — URL — key-pair-id ZDC4U0AZQ1RGC — private-key file://DEMOPRIKey.pem — date-less-than 2023–01–01
Just a few things to mention about using AWS CLI on the Mac OS terminal
When you generate your signed URL, it may include something like % at the end, this should not be included or you may see an error when trying to use the URL.
For me, the key pair id IS NOT from my root security credentials-CloudFront Key Pairs, this is the ID from the public Key I created under
For me, the — private-key file://DEMOPRIKey.pem was generated along with my public key using this online tool — more on that below. Remember to set the Key size to 2048, the default is 1024.
AWS CloudFront sign command can be run from your project folder which has all the required files such as keys.
If you haven’t used AWS CLI before you will need to install that first, and remember to set up your credentials using AWS configure, then enter specific info as prompted.
Using node js with Visual Studio Code
const AWS = require(‘aws-sdk’);
const fs = require(‘fs’);
const path = require(‘path’);
const distUrl = ‘’;
const s3Key = ‘’;
const cfAccessKeyId = ‘’;
let cfPrivateKey = fs.readFileSync(path.join(__dirname, ‘’));
const signer = new AWS.CloudFront.Signer(cfAccessKeyId, cfPrivateKey)
const thirtySeconds = 30 * 1000; // 30 seconds
let cfObjectUrl = ‘https://' + distUrl + ‘/’ + s3Key;
const signedUrl = signer.getSignedUrl({
url: cfObjectUrl,
expires: Math.floor(( + thirtySeconds)/1000)
Fire up a terminal window, make sure you run npm i aws-sdk, or simply install AWS toolkit from the Extensions Marketplace.
From the terminal window, simply run node signed.js and if successful you will see the signed URL generated.
Cloudfront Restricting Access — If you restrict viewer access, viewers must use CloudFront signed URLs or signed cookies to access your content.
Create a new key — use public key info from the above tool
Create a new key group — specify the Public key created in step 1
Go to Cloud front distributions, Behaviors, under restrict viewer access, yes, Trusted Key Groups, Add Key Groups from the drop-down, save changes and wait a bit for CloudFront to finish deploying.

Image description


Discussion (0)