将 Facebook 有效负载转换为 sha1 值以检查并匹配 x-hub-signation

Conversion of Facebook payload to sha1 value to check and match with x-hub-signation

我正在尝试实现 facebook webhook 安全性。

以下代码适用于短信,但在发送附件时,sha 值不匹配。

我尝试计算转义的 Unicode 小写有效负载,但结果对于简单文本也有不同的 sha 值。

任何帮助将不胜感激。

byte[] payloadBytes = request.inputStream.bytes

String hashReceived = xHubSignature.substring(5)

String hashComputed = HmacUtils.hmacSha1Hex(facebookAppSecret.getBytes(StandardCharsets.UTF_8), payloadBytes)

log.info('Received {} computed {}', hashReceived, hashComputed)

原来问题出在我访问数据的方式上,如下所示:

var express = require('express');
var app = express()
// Other imports 
app.listen(app.get('port'), ()=> 
{console.log('running on port', app.get('port'))});

请求正文是这样访问的:

  app.post('/webhook/',  (req, res)=> 
   {
    let body = req.body;
    //By this time the encoded characters were already decoded and hence the hashcheck was failing. 

    //processing the data 
   });

解决方案是使用 natice httpServer 创建服务器并访问数据,以便对原始数据进行哈希检查。

也许这也可以使用 Express 完成,但它对我不起作用。

这就是我所做的。

const http = require('http');
const url = require("url");
const crypto = require('crypto');

http.createServer((req, res) => {
    res.setHeader('Content-Type', 'text/html; charset=utf-8')

    let body = '';
    req.on('data', chunk => {
        body += chunk
    });

    if (urlItems.pathname === '/facebook/' && req.method === 'POST') {
        req.on('end', () => {

            let hmac = crypto.createHmac('sha1', appSecret);
            hmac.update(body, 'utf-8');
            let computedSig = `sha1=${hmac.digest('hex')}`;

            if (req.headers['x-hub-signature'] === computedSig) {
                 console.log(`${computedSig} matched ${req.headers['x-hub-signature']}`);
            } else {
                console.log(`Found ${computedSig} instead of ${req.headers['x-hub-signature']}`);
            }
            res.end(JSON.stringify({ status: 'ok' }))
        })
    }
}).listen(process.env.PORT || 3000);

编辑 1:由于基础设施的变化,我们切换到节点,因此节点代码。