DEV Community

AWS CloudFront — Secure URL Methods of Generation

AWS CLI on Mac OS

AWS CloudFront sign — URL https://.cloudfront.net/index.html — 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 https://console.aws.amazon.com/cloudfront/v3/home?region=us-east-2#/publickey
For me, the — private-key file://DEMOPRIKey.pem was generated along with my public key using this online tool — https://travistidwell.com/jsencrypt/demo/ 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 = ‘.cloudfront.net’;
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((Date.now() + thirtySeconds)/1000)
})
console.log(signedUrl)
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.
https://travistidwell.com/jsencrypt/demo/
https://console.aws.amazon.com/cloudfront/v3/home?region=us-east-2#/publickey
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

https://&response_type=token&scope=email+openid+phone+profile&redirect_uri=https://www.test.com/index.html?Expires=167200&Signature=

Discussion (0)