在 Cloud Code on Parse 上,我正在尝试验证从 Facebook webhook 收到的 header x-hub-signature。
secret
是 Facebook 应用程序的正确 key 。
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');
}
最后在您的 route 您可以将其用作:
app.post('/webhook/facebook', middlewares.fbWebhookAuth, facebook.webhook);
关于javascript - 验证 Facebook X-Hub-签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37946219/