繁体   English   中英

验证 Facebook X-Hub 签名

[英]Verify Facebook X-Hub-Signature

在 Parse 上的云代码上,我试图验证从 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']);

但签名永远不匹配。 怎么了?

你的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'); //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');
}

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

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

如果您使用中间件将正文解析为对象,请查看Node.js - 使用 Express 获取原始请求正文

如果你已经在使用原始解析模块,如果你没有JSON.stringify req.body,它应该可以工作:

payload = req.body,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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