1

我是 Express 的新手,我正在通过实现一个中间件来处理X-Hub-Signature如下所述:https ://pubsubhubbub.googlecode.com/git/pubsubhubbub-core-0.4.html#authednotify

express.json()在将请求传递到标准中间件以实际解码正文之前,我想添加一个处理此问题的中间件。

var sigVerifier = function(req, res, next) {

    var buf = '';
    // Need to accumulate all the bytes... <--- HOW TO DO THIS?

    // then calculate HMAC-SHA1 on the content.
    var hmac = crypto.createHmac('sha1', app.get('client_secret'));
    hmac.update(buf);
    var providedSignature = req.headers['X-Hub-Signature'];
    var calculatedSignature = 'sha1=' + hmac.digest(encoding='hex');
    if (providedSignature != calculatedSignature) {
        console.log(providedSignature);
        console.log(calculatedSignature);
        res.send("ERROR");
        return;
    }
    next();
};

app.use(sigVerifier);
app.use(express.json());
4

1 回答 1

1

Express 使用 connect 的 json 中间件。您可以将选项对象传递给 json 正文解析器,以在继续解析之前验证内容。

function verifyHmac(req, res, buf) {
  // then calculate HMAC-SHA1 on the content.
  var hmac = crypto.createHmac('sha1', app.get('client_secret'));
  hmac.update(buf);
  var providedSignature = req.headers['X-Hub-Signature'];
  var calculatedSignature = 'sha1=' + hmac.digest(encoding='hex');
  if (providedSignature != calculatedSignature) {
    console.log(
      "Wrong signature - providedSignature: %s, calculatedSignature: %s",
      providedSignature,
      calculatedSignature);
    var error = { status: 400, body: "Wrong signature" };
    throw error;
  }
}

app.use(express.json({verify: verifyHmac}));
于 2014-02-06T16:33:04.547 回答