Secure Webhook Example

node v10.24.1
version: 1.0.0
const crypto = require('crypto') // requestSignature // In your app, you will want to retrieve this from the 'X-Hub-Signature' header // Ex: const requestSignature = req.header('X-Hub-Signature') const requestSignature = 'sha1=b2493723c6ea6973fbda41573222c8ecb1c82666' // WEBHOOK_SECRET // In your app, you will want to retrieve this from a private environment variable // Ex: const WEBHOOK_SECRET = process.env.OPTIMIZELY_WEBHOOK_SECRET const WEBHOOK_SECRET = 'yIRFMTpsBcAKKRjJPCIykNo6EkNxJn_nq01-_r3S8i4' // Request Body // In your app, you will want to retrieve this value from the request and ensure it is parsed as a string // Ex: const requestBody = req.body const requestBody = '{"timestamp": 1558138293, "project_id": 11387641093, "data": {"cdn_url": "", "environment": "Production", "origin_url": "", "revision": 13}, "event": "project.datafile_updated"}' const hmac = crypto.createHmac('sha1', WEBHOOK_SECRET) const webhookDigest = hmac.update(requestBody).digest('hex') const computedSignature = `sha1=${webhookDigest}` console.log(`Request Signature: ${requestSignature}`); console.log(`Computed Signature: ${computedSignature}`); if (computedSignature === requestSignature) { console.log('Request signature matches computed signature. Webhook verified as secure!'); console.log('You have successfully verified that the Optimizely datafile has been updated'); } else { // Only respond to webhooks that you have verified are secure console.warn('Signatures do not match. Do not trust webhook as a secure webhook.'); }

no comments

    sign in to comment