Skip to content

Instantly share code, notes, and snippets.

@aarsilv
Created May 24, 2018 17:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aarsilv/c818bd080df8fa35be3e8ccc4dc0f9a5 to your computer and use it in GitHub Desktop.
Save aarsilv/c818bd080df8fa35be3e8ccc4dc0f9a5 to your computer and use it in GitHub Desktop.
Generating a signed s3 download url in node
// Creates a signed query string for getting private S3 files
// See "Query String Request Authentication Alternative" in https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html
// Node requirements
const crypto = require('crypto');
const querystring = require('querystring');
// Parameters
const AWS_BUCKET = 'my-bucket';
const AWS_KEY = 'MY:AWS:KEY';
const AWS_SECRET = 'MY:AWS:SECRET';
const PATH = '/path/to/file.ext';
// Build URL
const url = 'https://' + AWS_BUCKET + '.s3.amazonaws.com' + PATH;
// Expire in 30 minutes from now
const expiresEpocSeconds = Math.round(Date.now() / 1000) + 60 * 30;
// Combine and sign
const bucketAndPath = '/' + AWS_BUCKET + PATH;
const s3str = ['GET', '', '', expiresEpocSeconds, bucketAndPath].join('\n');
const signature = crypto.createHmac('sha1', AWS_SECRET).update(s3str).digest('base64');
// Create query string
const queryComponents = {
AWSAccessKeyId: AWS_KEY,
Expires: expiresEpocSeconds,
Signature: signature
};
const queryString = querystring.stringify(queryComponents);
// Build and output signed download url
const signedUrl = url + '?' + queryString;
console.log(signedUrl);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment