admin管理员组

文章数量:1400863

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?

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?

Share Improve this question edited Jun 21, 2016 at 14:02 GPack asked Jun 21, 2016 at 13:45 GPackGPack 2,4944 gold badges21 silver badges50 bronze badges 2
  • What’s the actual contant of payload, after you used JSON.stringify? – C3roe Commented Jun 21, 2016 at 15:12
  • the string representation of the JSON received in the body, starting with {"entry":[{"changes":[....... – GPack Commented Jun 21, 2016 at 15:17
Add a ment  | 

2 Answers 2

Reset to default 6

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,

本文标签: javascriptVerify Facebook XHubSignatureStack Overflow