JAVASCRIPT

Verify Webhook Signatures for Secure API Integrations (Node.js)

Secure your webhook endpoints by verifying incoming request signatures using a shared secret and cryptographic hashing, ensuring data integrity and authenticity in Node.js.

const express = require('express');
const crypto = require('crypto');
const bodyParser = require('body-parser');

const app = express();
const SECRET = 'my-super-secret-webhook-key'; // Replace with your actual secret

// Use bodyParser.raw() for webhook bodies to get the raw buffer
// This is crucial for signature verification as the hash must be computed on the raw body
app.use(bodyParser.raw({ type: 'application/json' }));

app.post('/webhook', (req, res) => {
  const signature = req.headers['x-hub-signature-256'] || req.headers['webhook-signature']; // Adjust header name as per API
  
  if (!signature) {
    return res.status(401).send('No signature provided.');
  }

  const hmac = crypto.createHmac('sha256', SECRET);
  // Compute hash from the raw request body buffer
  const digest = 'sha256=' + hmac.update(req.body).digest('hex');

  if (digest !== signature) {
    console.warn('Webhook signature mismatch!', { expected: digest, received: signature });
    return res.status(403).send('Invalid signature.');
  }

  // If signature matches, parse the body and process the webhook
  const payload = JSON.parse(req.body.toString());
  console.log('Webhook received and verified:', payload);
  res.status(200).send('Webhook processed successfully.');
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Webhook listener running on port ${PORT}`);
});
How it works: This Node.js snippet demonstrates how to verify webhook signatures using the `crypto` module. It's critical for security to ensure incoming webhook requests haven't been tampered with. The server computes a hash of the raw request body using a shared secret and compares it to the signature provided in the request headers. If they don't match, the request is rejected, preventing unauthorized or malicious payloads.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs