CloudFront Signed URLs with Node.js


This video is part of the following playlists:


Create signed urls to access files in a CloudFront distribution. Learn how to generate the signed URLs using a private key in a node application.

Chapters:

  • 0:00​ Intro
  • 0:42 Why Sign URLs?
  • 3:58 Generating an RSA Key Pair
  • 5:32 Create a Public Key in AWS
  • 6:41 Restrict CloudFront Access
  • 7:59 Sign URLs in Node Server
  • 12:21 Conclusion

Code Snippets

Generate RSA Key Pair

https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-trusted-signers.html

Install OpenSSL on your machine and generate the keypairs

openssl genrsa -out private_key.pem 2048
openssl rsa -pubout -in private_key.pem -out public_key.pem

Sign URLs

https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/modules/_aws_sdk_cloudfront_signer.html#getsignedurl

Install and import the cloudfront signer

npm i @aws-sdk/cloudfront-signer
import { getSignedUrl } from "@aws-sdk/cloudfront-signer"

Sign the urls before sending them to the browser

const signedUrl = getSignedUrl({
  keyPairId: process.env.CLOUDFRONT_KEYPAIR_ID,
  privateKey: process.env.CLOUDFRONT_PRIVATE_KEY,
  url: url,
  dateLessThan: new Date( Date.now() + (1000 /*sec*/ * 60))
})

Find an issue with this page? Fix it on GitHub