Skip to content

Instantly share code, notes, and snippets.

@chris-jamieson
Last active June 14, 2019 04:53
Show Gist options
  • Save chris-jamieson/e4ece159971c1c87e9053394b979f998 to your computer and use it in GitHub Desktop.
Save chris-jamieson/e4ece159971c1c87e9053394b979f998 to your computer and use it in GitHub Desktop.
GoCardless Node / Express signature verification middleware
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();
}
@bensbenj
Copy link

Good job! Thank you

@chris-jamieson
Copy link
Author

@bensbenj you are most welcome. Glad it helped you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment