javascript - 验证 Node/Express 中的 pubsubhubbub 内容签名

标签 javascript node.js express cryptography websub

我是 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());

最佳答案

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}));

关于javascript - 验证 Node/Express 中的 pubsubhubbub 内容签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19557887/

相关文章:

javascript - 使用AJAX形式更新数据库

node.js - Express.js - 类似 ASP.NET 的 MVC 路由

javascript - 使用Javascript计算小数点前后的位数

jquery - Socket.IO类型错误: Cannot read property 'broadcast' of undefined

javascript - 让 AJAX 与 Node.js 配合使用

node.js - 为什么在不使用 readFile 的 Sync 变体时该函数能够正确返回数据?

node.js - sequelize.js N :M through relationships, 删除级联

node.js - Node/Express 应用程序在与 MongoDB 交互时挂起,没有给出错误

javascript - 使用 requirejs 加载一个文件,里面有几个类(grunt-concat)

javascript - Electron(Atom Shell)应用程序中的用户设置存储在哪里?