Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

webhook validation endpoint #69

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/main/java/com/siftscience/utils/WebhookValidator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.siftscience.utils;

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 siftScienceSignature, String requestBody, String secretKey) {
String verificationSignature = SHA1 + new HmacUtils(HmacAlgorithms.HMAC_SHA_1, secretKey).hmacHex(requestBody);
if(siftScienceSignature.equals(verificationSignature))
return true;
else
return false;
}
}
48 changes: 48 additions & 0 deletions src/test/java/com/siftscience/WebhookValidatorTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
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.Assert;
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);

Assert.assertTrue(WebhookValidator.isValidWebhook(signature, requestBody, secretKey));
}

@Test
public void testWebhookValidationForInvalidSecretKey() {

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

Assert.assertFalse(WebhookValidator.isValidWebhook(signature, requestBody, "invalid key"));
}
}