Gabriel Temitope
Gabriel Temitope

Reputation: 113

Webhook Signature not matching (Nodejs)

I am trying to calculate the webhook signature coming Zum rails API with mine using HMAC with sha256 algorithm and base64, the payload is JSON stringify, and utf8. string, unfortunately for me, the signature doesn't match my calculation every time. If I make a request from my frontend, the signature doesn't match often. I tried to make the request from Postman and it always matches, I tried the same signature with a public webhook platform the signature matched. I checked the documentation.

Question: Why does it fail to match when the request is coming from my frontend but the signature and doesn't when I used the public webhook or postman?

Upvotes: 4

Views: 1038

Answers (1)

Gabriel Temitope
Gabriel Temitope

Reputation: 113

The issue was a string coming from the http request which I was retransforming into a string, causing the json item to switch places and only sometimes match the hmac secret.

I figured it out, by converting the raw body to verify the webhook signature. And then I used the req.rawBody directly in Hmac as the payload without reformating.

app.use(
   express.json({
      // We need the raw body to verify webhook signatures.

verify: function (req, res, buf) {

if (req.originalUrl.includes('webhook')) {

req.rawBody = buf.toString();
        
  }

  },

  })
);
const hash = crypto.createHmac('sha256', secret).update(req.rawBody, 'utf8').digest('base64')`;

Upvotes: 4

Related Questions