Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WooCommerce Webhooks Auth (secret & signature) - how to use

I'm trying to create an integration between WooCommerce Webhook API and my Node.js backend. However, I can't really figure out how I'm suppose to use the secret to authenticate the request.

secret: an optional secret key that is used to generate a HMAC-SHA256 hash of the request body so the receiver can verify authenticity of the webhook.

X-WC-Webhook-Signature: a Base64 encoded HMAC-SHA256 hash of the payload.

WooCommerce backend: (Hemmelighed = "Secret") enter image description here

Nodejs backend:

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

router.post('/', function (req, res) {
    var secret = 'ciPV6gjCbu&efdgbhfgj&¤"#&¤GDA';
    var signature = req.header("x-wc-webhook-signature");
    var hash = CryptoJS.HmacSHA256(req.body, secret).toString(CryptoJS.enc.Base64);

    if(hash === signature){
        res.send('match');
    } else {
        res.send("no match");
    }

});

Source: https://github.com/woocommerce/woocommerce/pull/5941

WooCommerce REST API source

The hash and the signature doesn't match. What is wrong?

Update: console.log returns these values:

hash: pU9kXddJPY9MG9i2ZFLNTu3TXZA++85pnwfPqMr0dg0=

signature: PjKImjr9Hk9MmIdUMc+pEmCqBoRXA5f3Ac6tnji7exU=

hash (without .toString(CryptoJS.enc.Base64)): a54f645dd7493d8f4c1bd8b66452cd4eedd35d903efbce699f07cfa8caf4760d

like image 443
Unicco Avatar asked Jan 07 '18 09:01

Unicco


1 Answers

The signature needs to be checked against the body and not the JSON it contains. i.e. the raw bytes of the req.body.

Modify the bodyParser first:

const rawBodySaver = (req, res, buf, encoding) => {
  if (buf && buf.length) {
    req.rawBody = buf.toString(encoding || 'utf8');
  }
};

app.use(bodyParser.json({ verify: rawBodySaver }));
app.use(bodyParser.urlencoded({ verify: rawBodySaver, extended: true }));
app.use(bodyParser.raw({ verify: rawBodySaver, type: '*/*' }));

and then, using crypto (it is distributed with node you don't need to npm install anything.)

import crypto from 'crypto'; //Let's try with built-in crypto lib instead of cryptoJS

router.post('/', function (req, res) {
  const secret = 'ciPV6gjCbu&efdgbhfgj&¤"#&¤GDA';
  const signature = req.header("X-WC-Webhook-Signature");

  const hash = crypto.createHmac('SHA256', secret).update(req.rawBody).digest('base64');

  if(hash === signature){
    res.send('match');
  } else {
    res.send("no match");
  }
});

like image 117
gokcand Avatar answered Sep 19 '22 12:09

gokcand