微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 HMAC sha256 和 base64 编码请求正文

如何解决使用 HMAC sha256 和 base64 编码请求正文

如何使用 HMAC sha 256 和 base64 对请求正文进行编码。

我从 xero webhook 收到的请求对象。

HEADER:
   "x-xero-signature" : HASH_VALUE
PAYLOAD:
  {
     "events": [],"lastEventSequence": 0,"firstEventSequence": 0,"entropy": "S0m3r4Nd0mt3xt"
  } 

xero 文档中的注释说“如果有效负载是使用 HMACSHA256 与您的 webhook 签名密钥和 base64 编码进行哈希处理的,它应该与标头中的签名匹配。这是一个正确签名的有效负载。如果签名与哈希值不匹配有效载荷,它是一个签名错误的有效载荷。”

我按照这个例子:https://devblog.xero.com/using-xero-webhooks-with-node-express-hapi-examples-7c607b423379

const express = require("express");
const router = express.Router();
const base64 = require('base-64');
const crypto = require('crypto')
const bodyParser = require('body-parser')
const xero_webhook_key = '00fRRlJBYiYN4ZGjmTtG+g/pulyb1Eru68YYL3PFoLsa78dadfQtGrOMuISuVBHxpXeEYo0Yy1Gc+hHMhDkSI/EEcgtrA==';

let options = {
    type: 'application/json'
  };
let itrBodyParser = bodyParser.raw(options);

router.post("/",itrBodyParser,async (req,res,next) =>{
//     console.log('::::WebhookPost:::');
const reSign = req.headers['x-xero-signature'];
 console.log(req.headers['x-xero-signature']);
 console.log('::::::::');
 console.log(req.body);
    console.log("Body: "+JSON.stringify(req.body))
    console.log(req.body.toString());
    console.log("Xero Signature: "+ reSign);
    console.log('Server key::::',xero_webhook_key);
    // Create our HMAC hash of the body,using our webhooks key
    let hmac = crypto.createHmac("sha256",xero_webhook_key).update(req.body.toString()).digest('base64');
    console.log("Resp Signature: ",hmac)

    if (req.headers['x-xero-signature'] == hmac) {
        res.statusCode = 200
    } else {
        res.statusCode = 401
    }
    console.log("Response Code: "+res.statusCode)
    return res.send();
 

});

解决方法

嘿,我最近做了一个关于使用 Xero 实现 webhooks 的 video,如果这让您感到困惑,请告诉我。我发现尝试以您的方式在路由上传递 itrBodyParser 对我不起作用,所以我在我的特定 webhooks 端点上使用 app.use 语句切换了它。如果您更喜欢书面指南而不是视频,这里是 blog post

,

我用这个解决方案解决了它。!我使用的是 express 框架,但请求没有像原始请求那样得到 .toString 也没有像 xero 文档中提到的那样工作。

 const server = http.createServer(async (req,resp) => {
  try {
      console.log(`::::Webhook::: ${webhookPort}`);
      console.log("::::x-xero-signature:::");
      console.log(req.headers["x-xero-signature"]);
      console.log(`--------------------------------------`);
      if (req.method === "POST") {
        if(req.headers["x-xero-signature"]){
          const rData = await new Promise((resolve,reject) => {
            return collectRequestData(req,(result) => {
                
                console.log(result);
                let hmac = crypto
                  .createHmac("sha256",xero_webhook_key)
                  .update(result)
                  .digest("base64");
                  console.log("Resp Signature: ",hmac);
                 
               
                return resolve({
                  hmac,result
                });
              });
          });
           console.log(">>Resp Signature: ",rData);
           console.log('>>x-xero-signature:::',req.headers["x-xero-signature"]);
           if(rData.result){
             const result = JSON.parse(rData.result);
             console.log('result:::',result);
             for(let { resourceId } of result.events) {
              console.log('::INVOICE ID = ',resourceId);
                getInvoiceData(resourceId);
             }
           }

           if(rData.hmac == req.headers["x-xero-signature"] ){
            console.log('::YES');
              resp.statusCode = 200;
          }else{
            console.log('::NO');
            resp.statusCode = 401;
          }
        }
        resp.end();
      }

        console.log("::::Webhookgetsssss:::");
        resp.message = 'Get API'
        resp.end();
     
  } catch (error) {
    resp.statusCode = 200;
    resp.end();
  }
      
     
  });
  server.listen(webhookPort);

function collectRequestData(request,callback) {
    let body = "";
    request.on("data",(chunk) => {
      body += chunk.toString();
    });
    request.on("end",() => {
      callback(body);
    });
  }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。