Last active
May 30, 2018 14:35
-
-
Save dominicfarr/806c876d0ecdb9dc1cbf7fc988b1f570 to your computer and use it in GitHub Desktop.
Mandrill Webhook Authentication in AWS Lambda function executed from AWS Gateway API
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
'use strict'; | |
const crypto = require("crypto"); | |
const {parse} = require('querystring'); | |
exports.handler = (event, context, callback) => { | |
const mandrillSignatureHeader = event.headers['X-Mandrill-Signature']; | |
const rawHTTPBody = event.body; // raw http application/x-www-form-urlencoded | |
const parsedBody = parse(rawHTTPBody); // parsed into an object | |
const theKeys = Object.keys(parsedBody); // get all the keys | |
// concat all elements for digest | |
const preHashValue = theKeys.reduce((joined, key) => `${joined}${key}${parsedBody[key]}`, process.env.WEBHOOK_URL); | |
// generate base64 digest | |
const digest = crypto.createHmac('sha1', process.env.WEBHOOK_KEY).update(preHashValue, 'utf8', 'binary').digest('base64'); | |
const signatureEquality = digest === mandrillSignatureHeader; | |
console.log("signature and digest ", signatureEquality ? "match" : "do not match"); | |
callback(null, {statusCode: signatureEquality ? 201 : 400}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks to @iperezqm for suggesting a better, future proof, preHashValue compute.
const preHashValue = theKeys.reduce((joined, key) =>
${joined}${key}${parsedBody[key]}, process.env.WEBHOOK_URL);