Skip to content

Instantly share code, notes, and snippets.

@ugurcemozturk
Created August 17, 2020 15:10
Show Gist options
  • Save ugurcemozturk/ef02f0b083ad6888c875812ff1dfe139 to your computer and use it in GitHub Desktop.
Save ugurcemozturk/ef02f0b083ad6888c875812ff1dfe139 to your computer and use it in GitHub Desktop.
Create a signed Cloudfront URL for an object in S3 on AWS
const AWS = require("aws-sdk");
var fs = require('fs');
exports.GetImage = async(event) => {
try {
let image = event['pathParameters']['img']
let ImageKey = `${process.env.IMAGE_FOLDER}/${image}`;
const cloudfrontAccessKeyId = process.env.CLOUDFRONT_KEY_ID;
const cloudFrontPrivateKey = fs.readFileSync('cloudfront-pk.pem', 'utf8');
const signer = new AWS.CloudFront.Signer(
cloudfrontAccessKeyId,
cloudFrontPrivateKey
);
const signedUrl = signer.getSignedUrl({
url: `https://${process.env.CLOUDFRONT_DOMAIN_NAME}/${ImageKey}`,
expires: Math.floor((Date.now() + process.env.URL_EXPIRE) / 1000),
});
let body = {
signed_image_url: decodeURI(signedUrl)
};
return {
statusCode: 200,
body: JSON.stringify(body),
};
} catch (err) {
console.log(err)
return {
statusCode: err.statusCode || 400,
body: err.message || JSON.stringify(err.message),
};
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment