The following example demonstrates how to securely verify signatures in PHP and validate the incoming webhook data. This approach ensures that the data received is authentic and unaltered.
<?php
$secretKey = 'your-signature-key';
// Get the raw POST data
$payload = file_get_contents('php://input');
// Get the signature sent with the request
$receivedSignature = $_SERVER['HTTP_X_SIGNATURE'] ?? '';
// Compute the HMAC signature using the payload and the secret key
$computedSignature = hash_hmac('sha256', $payload, $secretKey);
// Validate the signature
if (hash_equals($computedSignature, $receivedSignature)) {
$data = json_decode($payload, true);
http_response_code(200); // Success
echo "Webhook received successfully.";
} else {
http_response_code(400); // Invalid signature
echo "Invalid signature.";
}
?>
The following example demonstrates how to securely verify signatures in Node.js using the crypto module. This ensures the authenticity and integrity of incoming webhook payloads by validating the provided signature against a computed one.
const crypto = require('crypto');
// Secret key (Retrieve this from your database or environment variable)
const secretKey = 'your-signature-key';
// Middleware to parse JSON data
const express = require('express');
const app = express();
app.use(express.json());
// Webhook endpoint
app.post('/webhook', (req, res) => {
const payload = JSON.stringify(req.body);
const receivedSignature = req.get('X-Signature');
// Compute HMAC signature
const computedSignature = crypto.createHmac('sha256', secretKey).update(payload).digest('hex');
// Validate signature
if (receivedSignature === computedSignature) {
res.status(200).send('Webhook received successfully.');
} else {
res.status(400).send('Invalid signature.');
}
});
app.listen(3000, () => {
console.log('Server is listening on port 3000');
});
The following example demonstrates how to implement a secure webhook receiver in Python using the Flask framework. This example validates incoming requests by comparing the provided signature with a computed value to ensure the authenticity of the payload.
import hashlib
import hmac
from flask import Flask, request, jsonify
app = Flask(__name__)
# Secret key (Retrieve this from your database or environment variable)
secret_key = 'your-signature-key'
@app.route('/webhook', methods=['POST'])
def webhook():
payload = request.get_data()
received_signature = request.headers.get('X-Signature')
# Compute HMAC signature
computed_signature = hmac.new(secret_key.encode(), payload, hashlib.sha256).hexdigest()
# Validate signature
if hmac.compare_digest(computed_signature, received_signature):
return 'Webhook received successfully.', 200
else:
return 'Invalid signature.', 400
if __name__ == '__main__':
app.run(port=5000)
The following example demonstrates how to securely verify signatures in Ruby using the OpenSSL module. This approach ensures the integrity of incoming data by validating the provided signature against a computed value.
require 'openssl'
require 'json'
require 'sinatra'
# Secret key (Retrieve this from your database or environment variable)
SECRET_KEY = 'your-signature-key'
post '/webhook' do
payload = request.body.read
received_signature = request.env['HTTP_X_SIGNATURE']
# Compute HMAC signature
computed_signature = OpenSSL::HMAC.hexdigest('SHA256', SECRET_KEY, payload)
# Validate signature
if received_signature == computed_signature
status 200
body 'Webhook received successfully.'
else
status 400
body 'Invalid signature.'
end
end
The following example demonstrates how to implement signature verification in your Rails controller. This ensures that incoming webhook requests are authentic by comparing the computed signature with the one included in the request headers.
class WebhooksController < ApplicationController
protect_from_forgery except: :receive
SECRET_KEY = 'your-signature-key'
def receive
payload = request.raw_post
received_signature = request.headers['X-Signature']
# Compute HMAC signature
computed_signature = OpenSSL::HMAC.hexdigest('SHA256', SECRET_KEY, payload)
# Validate signature
if received_signature == computed_signature
head :ok
else
head :bad_request
end
end
end
The following Java example demonstrates how to securely verify signatures using the javax.crypto library. This implementation ensures the integrity and authenticity of incoming webhook payloads by comparing the computed signature with the one provided in the HTTP headers.
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/webhook")
public class WebhookReceiver {
private static final String SECRET_KEY = "your-signature-key";
@PostMapping
public ResponseEntity<String> receiveWebhook(@RequestBody String payload, @RequestHeader("X-Signature") String receivedSignature) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(payload.getBytes());
String computedSignature = Base64.getEncoder().encodeToString(hash);
if (computedSignature.equals(receivedSignature)) {
return ResponseEntity.ok("Webhook received successfully.");
} else {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid signature.");
}
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error processing webhook.");
}
}
}