Created
May 24, 2018 17:53
-
-
Save aarsilv/c818bd080df8fa35be3e8ccc4dc0f9a5 to your computer and use it in GitHub Desktop.
Generating a signed s3 download url in node
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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