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}); | |
}; |
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);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Mandrill webhooks allow authentication using a header signature.
How-to-Authenticate-Webhook-Requests
If you are using AWS Lambda function and an AWS Gateway API executing that lambda you need to process the raw http
application/x-www-form-urlencoded
body before constructing the value for hashing.Apologies for my poor JavaScript. If you see an improvement please add a comment and I will update accordingly.