it-source

WooCommerce Webhooks Auth (비밀 & 시그니처) - 사용방법

criticalcode 2023. 3. 2. 22:19
반응형

WooCommerce Webhooks Auth (비밀 & 시그니처) - 사용방법

WooCommerce 웹 훅 API와 Node.js 백엔드를 통합하려고 합니다.하지만 요청을 인증하기 위해 어떻게 비밀을 사용해야 하는지 잘 모르겠습니다.

secret:를 생성하기 위해 사용되는 옵션 개인 키HMAC-SHA256수신자가 웹 훅의 신뢰성을 확인할 수 있도록 요구 본문의 해시.

X-WC-Webhook-Signature:payload의 HMAC-SHA256 해시.

WooCommerce 백엔드: (Hemmelighted = "Secret")

노드 백엔드:

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");
    }

});

출처 : https://github.com/woocommerce/woocommerce/pull/5941

WooCommerce REST API 소스

해시와 서명이 일치하지 않습니다.뭐가 문제죠?

업데이트: console.log는 다음 값을 반환합니다.

hash: pU9kXddJPY9MG9i2ZFLNTu3TXZA++85pnwfPqMr0dg0=

signature: PJKImjr9Hk9MmIdUMC+pEmCqBoRXA5f3Ac6tnji7exU=

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

시그니처는 본문이 아닌 본문과 대조해야 합니다.를 들어, 시그니처는 본문에 포함되는 JSON, 즉 req.body의 raw 바이트와 대조해서는 안 됩니다.

의 변경bodyParser첫 번째:

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: '*/*' }));

다음으로 crypto를 사용합니다(필요없는 노드와 함께 배포됩니다).npm install모든 것)을 클릭합니다.

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");
  }
});

아래가 누군가의 시간을 절약해주길 바랍니다.

// Make sure to add a WISTIA_SECRET_KEY in your Environment Variables
// See https://docs.pipedream.com/environment-variables/
const secret = process.env.SELF_AUTOMATE_KEY;
const signature = event.headers["x-wc-webhook-signature"];
const body = steps.trigger.raw_event["body_b64"];
const clean_Body = body.replace("body_b64: ", "");
//const body = steps.trigger.raw_event;
console.log(event.headers["x-wc-webhook-signature"]);

console.log("Print Body", clean_Body);

if (process.env.SELF_AUTOMATE_KEY === undefined) {
  $end("No WISTIA_SECRET_KEY environment variable defined. Exiting.")
}

if (!("x-wc-webhook-signature" in event.headers)) {
  $end("No x-wc-webhook-signature header present in the request. Exiting.")
}

// Once we've confirmed we have a signature, we want to 
// validate it by generating an HMAC SHA-256 hexdigest
const crypto = require('crypto');

const hash = crypto.createHmac('sha256',
  secret).update(JSON.stringify(clean_Body), 'base64').digest('base64');



console.log(hash);
// $end() ends the execution of a pipeline, presenting a nice message in the "Messages"
// column in the inspector above. See https://docs.pipedream.com/notebook/code/#end
if (hash !== signature) {
  $end("The correct secret key was not passed in the event. Exiting!")
}

언급URL : https://stackoverflow.com/questions/48135995/woocommerce-webhooks-auth-secret-signature-how-to-use

반응형