Skip to content

Instantly share code, notes, and snippets.

@heri16
Last active February 20, 2021 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heri16/333cab4cafeec97f5207f090dbedfcae to your computer and use it in GitHub Desktop.
Save heri16/333cab4cafeec97f5207f090dbedfcae to your computer and use it in GitHub Desktop.
Upload with cloudfront signature
const bucketName = "";
const bucketEnpoint = "";
const s3 = new AWS.S3({
params: { Bucket: bucketName },
endpoint: bucketEndpoint,
s3BucketEndpoint: true,
// s3DisableBodySigning: false,
computeChecksums: true,
correctClockSkew: true,
});
function signCloudfront(req, done) {
// This listener is called after the AWS Signature Version 4 headers have been added to req.httpRequest.headers,
// but before the request is sent.
const service = req.service;
// REST or GRAPHQL Query to remote server which will call AWS.CloudFront.Signer.getSignedUrl()
// Remote server stores the Cloudfront privateKey
// See: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudFront/Signer.html#getSignedUrl-property
// See: https://javascript.info/fetch
const requestData = {
url: `${keyPrefix}/*`
};
const request = new Request("https://api.lawkin.com/cloudfront/sign", {
method: "POST",
cache: "no-store",
headers: {
"Content-Type": "application/json;charset=utf-8",
Authorization: "Bearer xxxxxxxxx"
},
body: JSON.stringify(requestData)
});
fetch(request)
.then((response) => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
})
.then((data) => {
// Append search to href
req.httpRequest.path += new Url(data.signedUrl).search;
})
.then(
() => {
done();
},
(err) => {
req.response.error = err;
done();
}
);
}
const request = s3.upload({ Key: value, Body: stream }));
// See: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Request.html#sign-event
request.onAsync('sign', signCloudfront)
request.promise().then(console.log, console.error)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment