AWS Developer Tools Blog
Creating Amazon CloudFront Signed URLs in Node.js
Amazon CloudFront allows you to use signed URLs to restrict access to content. This allows you to securely serve private content, or content intended for selected users using CloudFront. Read more about how CloudFront signed URLs work.
This article describes how to generate Amazon CloudFront signed URLs in Node.js.
To generate signed URLs, you can use the aws-cloudfront-sign npm module.
Installing the module
npm install aws-cloudfront-sign
Using the module in your code
We recommend that you restrict direct access to your bucket, and require that users access content only through CloudFront. Read more about using an origin access identity to restrict access to Amazon S3 content.
To create a signed URL, you first need to configure your distribution to specify which AWS accounts can create signed URLs (trusted signers). You then need to create a CloudFront key pair for your trusted signer. Once you’ve downloaded your private key for the key-pair ID (Access Key ID), you can use it in your code to generate signed URLs.
The following code shows how to generate signed URLS for web distributions:
var cfsign = require('aws-cloudfront-sign');
var signingParams = {
keypairId: process.env.PUBLIC_KEY,
privateKeyString: process.env.PRIVATE_KEY,
// Optional - this can be used as an alternative to privateKeyString
privateKeyPath: '/path/to/private/key',
expireTime: 1426625464599
}
// Generating a signed URL
var signedUrl = cfsign.getSignedUrl(
'http://example.cloudfront.net/path/to/s3/object',
signingParams
);
This module can also be used to generate signed URLs for RTMP distributions:
var signedRTMPUrlObj = cfsign.getSignedRTMPUrl(
'example.cloudfront.net',
// Must not contain prefixes like mp3: or mp4:
'path/to/s3/object',
signingParams
);
This generated URL can now be served to users who are entitled to access the content. We hope this simplifies creating signed URLs for Amazon CloudFront in Node.js.