Reputation: 2504
On Cloud Code on Parse Im trying to verify the header x-hub-signature received from Facebook webhook.
secret
is the right secret-key of the Facebook app.
var
hmac,
expectedSignature,
payload = JSON.stringify(req.body),
secret = 'xyzxyzxyz';
hmac = crypto.createHmac('sha1', secret);
hmac.update(payload, 'utf-8');
expectedSignature = 'sha1=' + hmac.digest('hex');
console.log(expectedSignature);
console.log(req.headers['x-hub-signature']);
but the signatures never match. What is wrong?
Upvotes: 3
Views: 4596
Reputation: 11780
Your bodyParserJSON
should return rawBody:
bodyParser.json({
verify(req, res, buf) {
req.rawBody = buf;
},
})
Here is a middleware that I've written. It uses crypto
module to generate sha1
fbWebhookAuth: (req, res, next) => {
const hmac = crypto.createHmac('sha1', process.env.FB_APP_SECRET);
// hmac.update(req.rawBody, 'utf-8'); //older versions
hmac.update(req.rawBody, 'utf8');
if (req.headers['x-hub-signature'] === `sha1=${hmac.digest('hex')}`) next();
else res.status(400).send('Invalid signature');
}
and finally in your route you can use it as:
app.post('/webhook/facebook', middlewares.fbWebhookAuth, facebook.webhook);
Upvotes: 6
Reputation: 137
If you're parsing the body into an object with middleware, check out Node.js - get raw request body using Express
If you're already using the raw parsing module, it should work if you don't JSON.stringify
req.body:
payload = req.body,
Upvotes: 1