Skip to content

Instantly share code, notes, and snippets.

@miguelpeixe
Last active March 5, 2018 08:48
Show Gist options
  • Select an option

  • Save miguelpeixe/d4ab50d3698fd4455569f133726d0565 to your computer and use it in GitHub Desktop.

Select an option

Save miguelpeixe/d4ab50d3698fd4455569f133726d0565 to your computer and use it in GitHub Desktop.
Express raw body for Facebook Hub Signature validation
const express = require('express');
const bodyParser = require('body-parser');
const crypto = require('crypto');
const app = express();
// Use json body parser when content is `application/json` type and request headers does not include `x-hub-signature`
app.use(bodyParser.json({
type: req => req.headers['content-type'] == 'aplication/json' && !req.headers['x-hub-signature']
}));
// Use raw body parser when headers include `x-hub-signature`
app.use(bodyParser.raw({
type: req => !!req.headers['x-hub-signature']
}));
app.use(bodyParser.urlencoded({ extended: true }));
const verificationToken = 'your-token';
const clientSecret = 'your-app-secret';
// Hub signature verification middleware
const verifyHubSignature = function (req, res, next) {
const signature = req.headers['x-hub-signature'];
if(signature !== undefined && Buffer.isBuffer(req.body)) {
const hmac = crypto.createHmac('sha1', clientSecret);
hmac.update(req.body);
const expectedSignature = 'sha1=' + hmac.digest('hex');
if(expectedSignature !== signature) {
res.status(400).send('Invalid signature');
} else {
next();
}
} else {
next();
}
}
app.use('/subscriptions', verifyHubSignature, function(req, res) {
// Authorize subscription
if(req.query['hub.mode'] == 'subscribe' && req.query['hub.verify_token'] == verificationToken) {
res.status(200).send(req.query['hub.challenge']);
// Subscription update
} else if(req.headers['x-hub-signature']) {
console.log('verified');
res.sendStatus(200);
} else {
res.sendStatus(400);
}
});
@shaunthegeek
Copy link

LINE8 "aplication" should be "application"

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