From 6431650591d9e2f1b84df02c2140fac2a8fd9ec0 Mon Sep 17 00:00:00 2001 From: Sreejith Kalapurakkal Date: Wed, 29 Dec 2021 15:48:45 +0530 Subject: [PATCH] webhook validation --- .../siftscience/utils/WebhookValidator.java | 17 +++++++++++ .../com/siftscience/WebhookValidatorTest.java | 28 +++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 src/main/java/com/siftscience/utils/WebhookValidator.java create mode 100644 src/test/java/com/siftscience/WebhookValidatorTest.java diff --git a/src/main/java/com/siftscience/utils/WebhookValidator.java b/src/main/java/com/siftscience/utils/WebhookValidator.java new file mode 100644 index 0000000..4a90aa7 --- /dev/null +++ b/src/main/java/com/siftscience/utils/WebhookValidator.java @@ -0,0 +1,17 @@ +package com.siftscience.utils; + +import com.siftscience.exception.SiftException; +import org.apache.commons.codec.digest.HmacAlgorithms; +import org.apache.commons.codec.digest.HmacUtils; + +public class WebhookValidator { + private static final String SHA1 = "sha1="; + + public static boolean isValidWebhook(String requestBody, String secretKey, String siftScienceSignature) { + String verificationSignature = SHA1 + new HmacUtils(HmacAlgorithms.HMAC_SHA_1, secretKey).hmacHex(requestBody); + if(siftScienceSignature.equals(verificationSignature) ) + return true; + else + throw new SiftException("Unauthenticated webhook"); + } +} diff --git a/src/test/java/com/siftscience/WebhookValidatorTest.java b/src/test/java/com/siftscience/WebhookValidatorTest.java new file mode 100644 index 0000000..930ea7f --- /dev/null +++ b/src/test/java/com/siftscience/WebhookValidatorTest.java @@ -0,0 +1,28 @@ +package com.siftscience; + +import com.siftscience.utils.WebhookValidator; +import org.apache.commons.codec.digest.HmacAlgorithms; +import org.apache.commons.codec.digest.HmacUtils; +import org.junit.Test; + +public class WebhookValidatorTest { + + @Test + public void testWebhookValidation() { + + final String secretKey = "1d708fe409f22591"; + final String requestBody = "{\n" + + " \"entity\": {\n" + + " \"type\": \"user\",\n" + + " \"id\": \"USER123\"\n" + + " },\n" + + " \"decision\": {\n" + + " \"id\": \"block_user_payment_abuse\"\n" + + " },\n" + + " \"time\": 1461963439151\n" + + "}"; + final String signature = "sha1=" + new HmacUtils(HmacAlgorithms.HMAC_SHA_1, secretKey).hmacHex(requestBody); + + WebhookValidator.isValidWebhook(requestBody, secretKey, signature); + } +}