简体   繁体   English

验证 Facebook X-Hub 签名

[英]Verify Facebook X-Hub-Signature

On Cloud Code on Parse Im trying to verify the header x-hub-signature received from Facebook webhook.在 Parse 上的云代码上,我试图验证从 Facebook webhook 收到的标头x-hub-signature

secret is the right secret-key of the Facebook app. 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']);

but the signatures never match.但签名永远不匹配。 What is wrong?怎么了?

Your bodyParserJSON should return rawBody :你的bodyParserJSON应该返回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它使用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');
}

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

If you're already using the raw parsing module, it should work if you don't JSON.stringify req.body:如果你已经在使用原始解析模块,如果你没有JSON.stringify req.body,它应该可以工作:

payload = req.body,

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

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