Search code examples
node.jstwitterwebhookskoa

Securing Twitter Webhook


As mentioned in Twitter Docs Steps to validate a request

  1. Create a hash using your consumer secret and incoming payload body.
  2. Compare created hash with the base64 encoded x-twitter-webhooks-signature value.

Here is my code for doing so:

const buffer = Buffer.from(JSON.stringify(ctx.request.body))
const expectedHash = crypto.createHmac('sha256', TWITTER_CONSUMER_SECRET).update(buffer).digest('base64')

The x-twitter-webhooks-signature header from twitter and the hash generated does not match. Also, the post at https://twittercommunity.com/t/validating-the-webhook-signature-header-in-node-js/102525 says that it's JSON.stringify() issue. I'm using koa and koa-body, how can I fix the hash mismatch?


Solution

  • Found a solution. Used koa-bodyparser instead of koa-body then sha256 of ctx.request.rawBody matches with the header.