简体   繁体   中英

Verify Facebook X-Hub-Signature

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?

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);

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,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM