在 Express.js 中验证 Kentico Cloud webhooks 签名

Validating Kentico Cloud webhooks signatures in Express.js

如何使用 express.js 验证 webbooks 签名?

在文档中,有一节关于 notification signatures 但我不知道如何将它与 Express.js

结合起来

This question is a migrated from official Kentico Cloud Forum, that would be deleted.

在 API 参考中,there is a sample 描述了各种语言的 webhook 验证,包括 node.js。

如果您想使用 express.js,您可以从这个模板代码开始:

const express = require('express');
const crypto = require('crypto');

// Create a new instance of express
const app = express();

// Set up a raw bodyparser to read the webhook post
const bodyParserRaw = require('body-parser').raw({
    type: '*/*',
});

function webhookValidator (req, res, next) {
    // get the header signature from the webhook request
    const givenSignature = req.headers['x-kc-signature'];

    // throw error if it's missing
    if (!givenSignature) {
        console.log('Missing signature');
        return res.status(409).json({
            error: 'Missing signature'
        });
    }

    // create HMAC from the raw request body
    let hmac = crypto.createHmac('sha256', [your-webhook-secret-key]);
    hmac.write(req.body);
    hmac.end();

    // get a base64 hash from HMAC
    let hash = hmac.read().toString('base64');

    // check validity with timingSafeEqual
    let webhookValid = false;
    try {
        webhookValid = crypto.timingSafeEqual(Buffer.from(givenSignature, 'base64'), Buffer.from(hash, 'base64'));
    } catch (e) {
        webhookValid = false
    }

    // return validity
    if (webhookValid) {
        return next();
    } else {
        console.log('Invalid signature');
        return res.status(409).json({
            error: 'Invalid signature'
        });
    }
}

// create a route and pass through the bodyparser and validator
app.post('/webhook', bodyParserRaw, webhookValidator, ( req, res, next ) => {
    // If execution gets here, the HMAC is valid
    console.log('webhook is valid');
});

编辑

您可以使用 Kontent webhook 帮助程序库来快速验证 webhook 通知及其签名。该库作为 @kentico/kontent-webhook-helper npm 包提供,可帮助您避免计算哈希值时的常见问题。