如何使用HMAC sha 256和base64编码请求主体。
我从Xero Webhook接收的请求对象。
来自 Xero 文档的说明称:“如果使用 HMACSHA256 用您的 Webhook 签名密钥对有效载荷进行哈希处理并进行 base64 编码,则应该与标头中的签名相匹配。这是正确签名的有效载荷。 如果签名与哈希载荷不匹配,则为不正确签名的有效载荷。”
我遵循了这个例子:https://devblog.xero.com/using-xero-webhooks-with-node-express-hapi-examples-7c607b423379。
我从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();
});