jasonsims / aws-cloudfront-sign

Utility module for AWS CloudFront
MIT License
175 stars 80 forks source link

AWS CloudFront URL Signature Utility

Build Status npm version


NOTE

The AWS SDK for JavaScript has added support for generating signed URLs and Cookies. Please see Class: AWS.CloudFront.Signer


Generating signed URLs for CloudFront links is a little more tricky than for S3. It's because signature generation for S3 URLs is handled a bit differently than CloudFront URLs and this functionality is not currently supported by the aws-sdk library for JavaScript. In case you also need to do this, I've created this simple utility to make things easier.

Usage

Requirements

Configuring CloudFront

  1. Create a CloudFront distribution
  2. Configure your origin with the following settings:

    Origin Domain Name: {your-s3-bucket} Restrict Bucket Access: Yes Grant Read Permissions on Bucket: Yes, Update Bucket Policy

  3. Create CloudFront Key Pair. more info

Installing

npm install aws-cloudfront-sign

TypeScript

import { SignatureOptions } from 'aws-cloudfront-sign/types'

Upgrading from 2.x to 3.x

Upgrading from 1.x to 2.x

API

getSignedUrl(url, options)

getSignedCookies(url, options)

getSignedRTMPUrl(domainName, s3key, options)

⛔️ Deprecated: RTMP Support Discontinuing on December 31, 2020

Options

Examples

Creating a signed URL

By default the URL will expire after half an hour.

// ESM: import { getSignedUrl } from 'aws-cloudfront-sign'
const cf = require('aws-cloudfront-sign')
const options = {keypairId: 'APKAJM2FEVTI7BNPCY4A', privateKeyPath: '/foo/bar'}
const signedUrl = cf.getSignedUrl('http://xxxxxxx.cloudfront.net/path/to/s3/object', options);
console.log('Signed URL: ' + signedUrl);

Creating signed cookies

// ESM: import { getSignedCookies } from 'aws-cloudfront-sign'
const cf = require('aws-cloudfront-sign')
const options = {keypairId: 'APKAJM2FEVTI7BNPCY4A', privateKeyPath: '/foo/bar'}
const signedCookies = cf.getSignedCookies('http://xxxxxxx.cloudfront.net/*', options);

// You can now set cookies in your response header. For example:
for(var cookieId in signedCookies) {
 res.cookie(cookieId, signedCookies[cookieId]);
}