节点js中的Sendgrid webhook签名验证失败

问题描述 投票:0回答:0

我正在尝试在 node.js 中验证 Sendgrid 的 webhooks 的签名,但我遇到了一致的验证失败。我尝试过使用“测试集成”功能、“测试电子邮件”进行单次发送以及实际发送,但所有这些选项最终都以验证失败告终。

我正在使用 node.js 的官方帮助程序,可在此处获取:https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/eventwebhook/src/eventwebhook.js 请注意,这是在 Cloud Functions 上实现的。

import * as functions from "firebase-functions";
import { EventWebhook } from "@sendgrid/eventwebhook";

export const handleSendGridWebhookEvents = functions
  .region(...fb.REGIONS)
  .https.onRequest(async (req, resp) => {

    const signature =
      (req.get("x-twilio-email-event-webhook-signature") as string) ??
      "";
    const timestamp =
      (req.get("x-twilio-email-event-webhook-timestamp") as string) ??
      "";

    if (!signature || !timestamp) {
      resp.json({
        error: "Webhook handler failed",
      });
      throw new Error("Sendgrid headers missing");
    }

    const verify = new EventWebhook();
    const payload = req.body;
    const publicKey = process.env.SENDGRID_WEBHOOK_PK

    try {
      const ecdsaPublicKey = verify.convertPublicKeyToECDSA(publicKey);
      const isVerified = verify.verifySignature(
        ecdsaPublicKey,
        payload,
        signature,
        timestamp
      );
      console.log({ isVerified }); // Always returns false
      resp.status(200);
    } catch (e) {
      throw e;
    }
    resp.json({ received: true });
  });

我也尝试过直接使用公钥而不进行初始转换为 ECDSA,但也没有运气。

是否需要任何额外的步骤来验证签名?或者上面的代码有什么问题......?

谢谢

node.js webhooks sendgrid
© www.soinside.com 2019 - 2024. All rights reserved.