Request signature verification in Node.js
Overview
By exposing a public endpoint to receive events from RemoveBounce, it is important to understand the security implications.
This article presents a sample implementation of a request signature in Node.js.
Dependencies
This example uses only the core dependency crypto
from Node.js.
Requirements
You need your webhook shared secret available. You can find it here.
Headers
Each request sent from RemoveBounce API will have the following headers:
x-rb-webhook-signature
x-rb-webhook-timestamp
The signature is generated using the SHA-256 algorithm using the API secret as secret and based on the following data:
- timestamp – The same value as in the
x-rb-webhook-timestamp
header. - body – A string from the body for POST or an empty string for other methods.
Example
const crypto = require( 'crypto' );
// Extract the signature and the timestamp from the request headers
const receivedSignature = request.headers['x-rb-webhook-signature'];
const receivedTimestamp = request.headers['x-rb-webhook-timestamp'];
// This is an example function on how to validate the request
function isSignatureValid(receivedSignature, webhookSharedSecret, timestamp, body) {
const hmac = crypto.createHmac('SHA256', webhookSharedSecret);
hmac.update(`${ timestamp }`);
if (body) {
hmac.update(Buffer.from(JSON.stringify( body )));
}
const signature = hmac.digest('hex');
return signature === receivedSignature;
}
console.log(isSignatureValid(receivedSignature, webhookSharedSecret, receivedTimestamp, request.body));