Last active
June 14, 2019 04:53
-
-
Save chris-jamieson/e4ece159971c1c87e9053394b979f998 to your computer and use it in GitHub Desktop.
GoCardless Node / Express signature verification middleware
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
const crypto = require('crypto'); | |
/** | |
* Express middleware to validate incoming webhook request from Gocardless | |
* @param {*} req Express request | |
* @param {*} res Express response | |
* @param {*} next Next middleware function if succeeds | |
*/ | |
function verifyGocardlessWebhook(req, res, next) { | |
if (!req.headers['webhook-signature']) { | |
// throw bad request | |
res.status(httpStatus.BAD_REQUEST); | |
res.json({ message: '"Webhook-signature" header not set' }); | |
return null; | |
} | |
// assuming req has been passed through express JSON bodyparser | |
const bodyAsString = JSON.stringify(req.body, null, 0); // needs to be stringified | |
const secret = config.gocardlessWebhookSecret; // get this from environment variables | |
const hash = crypto.createHmac('sha256', secret).update(bodyAsString).digest('hex'); | |
if (hash !== req.headers['webhook-signature']) { | |
// signatures do not match | |
res.status(498); // 498 INVALID TOKEN | |
res.json({ message: 'Invalid token' }); | |
return null; | |
} | |
// otherwise, looks good, continue to next middleware | |
return next(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks good. I approve this snippet.