验证Facebook X-Hub-Signature

时间:2016-06-21 13:45:16

标签: javascript node.js facebook parse-platform webhooks

On Parse上的Cloud Code我试图验证从Facebook webhook收到的标题 x-hub-signature

secret是Facebook应用程序的正确秘密密钥。

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

但签名永远不会匹配。 有什么问题?

2 个答案:

答案 0 :(得分:2)

您的bodyParserJSON应该返回 rawBody

bodyParser.json({
    verify(req, res, buf) {
      req.rawBody = buf;
    },
})

这是我写过的中间件。它使用crypto模块生成sha1

fbWebhookAuth: (req, res, next) => {
    const hmac = crypto.createHmac('sha1', process.env.FB_APP_SECRET);
    hmac.update(req.rawBody, 'utf-8');
    if (req.headers['x-hub-signature'] === `sha1=${hmac.digest('hex')}`) next();
    else res.status(400).send('Invalid signature');
}

最后在您的路线中,您可以将其用作:

app.post('/webhook/facebook', middlewares.fbWebhookAuth, facebook.webhook);

答案 1 :(得分:1)

如果您正在将主体解析为具有中间件的对象,请查看Node.js - get raw request body using Express

如果你已经在使用原始解析模块,那么如果你没有JSON.stringify req.body:

它应该可以工作
payload = req.body,
相关问题