Java webhooks: a Spring Boot endpoint with signature checks
byte[], verify its HMAC-SHA256 signature in constant time, skip duplicate deliveries and process events asynchronously. The signature class uses only the JDK, so it also works in Quarkus, Micronaut or a plain servlet.By the HookWatcher team · Updated
What you'll build
The endpoint receives GitHub webhooks, but the pattern is the same for any provider that signs with HMAC-SHA256. In order, the Spring Boot handler:
- verifies
X-Hub-Signature-256over the raw body bytes, before anything parses them, and answers401if it doesn't match; - requires an
X-GitHub-DeliveryID and parses the JSON (400if either is missing or broken); - skips a delivery ID it has already processed with a
200, so GitHub records success and the event runs once; - answers
202straight away and does the work after the response, because GitHub gives up after 10 seconds.
| Request | Status | Body |
|---|---|---|
| Valid signature, new delivery | 202 | accepted |
| Same delivery ID again | 200 | duplicate |
| Missing or wrong signature, or body changed after signing | 401 | invalid signature |
| Valid signature, no delivery ID or not JSON | 400 | missing delivery id / invalid JSON |
Tested with Spring Boot 4.1.1 (Spring Framework 7, Jackson 3, embedded Tomcat 11) on Java 25, compiled for Java 17, Spring Boot 4's baseline.
Set up the project
Generate a Maven project with Spring MVC on start.spring.io, or create these files by hand:
webhooks/
├── pom.xml
└── src/
├── main/java/com/example/webhooks/
│ ├── WebhooksApplication.java
│ ├── GitHubSignature.java
│ ├── GitHubWebhookController.java
│ └── GitHubEventHandler.java
├── main/resources/application.properties
└── test/java/com/example/webhooks/GitHubSignatureTest.java<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.1.1</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>webhooks</artifactId>
<version>0.0.1</version>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project># Startup fails if GITHUB_WEBHOOK_SECRET isn't set.
github.webhook-secret=${GITHUB_WEBHOOK_SECRET}package com.example.webhooks;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync
public class WebhooksApplication {
public static void main(String[] args) {
SpringApplication.run(WebhooksApplication.class, args);
}
}Verify the signature
MessageDigest.isEqual is the JDK's constant-time comparison: its documentation says the time depends only on the length of the first array, not on the contents. String.equals and Arrays.equals return at the first difference. An empty secret is refused outright, so a missing configuration can never make every request "valid".
package com.example.webhooks;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public final class GitHubSignature {
private GitHubSignature() {}
/** True when header is "sha256=" + the hex HMAC-SHA256 of the raw body. */
public static boolean verify(byte[] body, String header, byte[] secret) {
if (header == null || !header.startsWith("sha256=") || secret.length == 0) return false;
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret, "HmacSHA256"));
byte[] expected = ("sha256=" + HexFormat.of().formatHex(mac.doFinal(body)))
.getBytes(StandardCharsets.US_ASCII);
// Time depends only on the length of expected, not on where the bytes differ.
return MessageDigest.isEqual(expected, header.getBytes(StandardCharsets.US_ASCII));
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
}package com.example.webhooks;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Test;
class GitHubSignatureTest {
// GitHub's published test values (docs: Validating webhook deliveries).
static final byte[] SECRET = "It's a Secret to Everybody".getBytes(StandardCharsets.UTF_8);
static final byte[] BODY = "Hello, World!".getBytes(StandardCharsets.UTF_8);
static final String SIGNATURE =
"sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17";
@Test
void acceptsGitHubsTestSignature() {
assertTrue(GitHubSignature.verify(BODY, SIGNATURE, SECRET));
}
@Test
void rejectsChanges() {
assertFalse(GitHubSignature.verify("Hello, World?".getBytes(StandardCharsets.UTF_8), SIGNATURE, SECRET));
assertFalse(GitHubSignature.verify(BODY, SIGNATURE, "another secret".getBytes(StandardCharsets.UTF_8)));
assertFalse(GitHubSignature.verify(BODY, SIGNATURE.substring(0, SIGNATURE.length() - 1), SECRET));
assertFalse(GitHubSignature.verify(BODY, null, SECRET));
}
}mvn test # ./mvnw test in a project generated by start.spring.io
The controller
@RequestBody byte[] hands you the bytes exactly as received. Bind it to a String and they go through charset decoding; bind it to a DTO and Jackson rebuilds the object; neither is what GitHub signed. Parse with Spring's configured JsonMapper only after the check. Set.add on a concurrent set is atomic, so two simultaneous redeliveries can't both get through.
package com.example.webhooks;
import java.nio.charset.StandardCharsets;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
@RestController
public class GitHubWebhookController {
private final byte[] secret;
private final JsonMapper json;
private final GitHubEventHandler handler;
// Processed delivery IDs; use a unique database key in production.
private final Set<String> seen = ConcurrentHashMap.newKeySet();
public GitHubWebhookController(@Value("${github.webhook-secret}") String secret,
JsonMapper json, GitHubEventHandler handler) {
this.secret = secret.getBytes(StandardCharsets.UTF_8);
this.json = json;
this.handler = handler;
}
@PostMapping("/webhooks/github")
public ResponseEntity<String> receive(
@RequestBody(required = false) byte[] body, // raw bytes, not a DTO or String
@RequestHeader(name = "X-Hub-Signature-256", required = false) String signature,
@RequestHeader(name = "X-GitHub-Delivery", required = false) String delivery,
@RequestHeader(name = "X-GitHub-Event", required = false) String event) {
byte[] raw = body == null ? new byte[0] : body;
if (!GitHubSignature.verify(raw, signature, secret)) return text(401, "invalid signature");
if (delivery == null || delivery.isBlank()) return text(400, "missing delivery id");
JsonNode payload;
try {
payload = json.readTree(raw);
} catch (JacksonException e) {
return text(400, "invalid JSON");
}
if (!seen.add(delivery)) return text(200, "duplicate"); // add() is atomic
handler.handle(event, payload);
return text(202, "accepted");
}
private static ResponseEntity<String> text(int status, String body) {
return ResponseEntity.status(status).contentType(MediaType.TEXT_PLAIN).body(body);
}
}The @Async handler runs on Spring's task executor after the controller returns, which is why @EnableAsync is on the application class. Replace it with a persistent queue (a database outbox, JMS, Kafka) when losing an event on restart isn't acceptable.
package com.example.webhooks;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import tools.jackson.databind.JsonNode;
@Service
public class GitHubEventHandler {
private static final Logger log = LoggerFactory.getLogger(GitHubEventHandler.class);
@Async // runs on another thread, after the controller returns; use a job queue in production
public void handle(String event, JsonNode payload) {
log.info("{} {} {}", event, payload.path("action").asString(""),
payload.path("repository").path("full_name").asString(""));
}
}Run it and test it
export GITHUB_WEBHOOK_SECRET="It's a test secret" mvn spring-boot:run # Tomcat started on port 8080
In a second terminal, save this script as test-webhook.sh. It signs requests with openssl exactly like GitHub does and checks each status code against the table above. It's the same script for every tutorial in this series, so it also tells you whether a port to another framework behaves the same.
#!/usr/bin/env bash
# Sends five deliveries to a GitHub webhook handler and checks each status code.
# Usage: GITHUB_WEBHOOK_SECRET='...' ./test-webhook.sh http://localhost:3000/webhooks/github
set -u
URL="${1:?usage: test-webhook.sh URL}"
SECRET="${GITHUB_WEBHOOK_SECRET:?set GITHUB_WEBHOOK_SECRET}"
BODY='{"action":"opened","issue":{"number":1347,"title":"Found a bug"},"repository":{"full_name":"octocat/Hello-World"}}'
ID="test-$(date +%s)-$$"
FAILED=0
sign() { printf '%s' "$1" | openssl dgst -sha256 -hmac "$SECRET" | sed 's/^.*= //'; }
send() { # body, signature ("" = none), delivery ID
local args=(-s -o /dev/null -w '%{http_code}' -X POST "$URL"
-H 'Content-Type: application/json' -H 'X-GitHub-Event: issues' -H "X-GitHub-Delivery: $3")
[ -n "$2" ] && args+=(-H "X-Hub-Signature-256: sha256=$2")
curl "${args[@]}" --data-binary "$1"
}
check() { # name, status received, status expected
if [ "$2" = "$3" ]; then echo "ok $1 ($2)"; else echo "FAIL $1: expected $3, got $2"; FAILED=1; fi
}
SIG=$(sign "$BODY")
check "valid delivery" "$(send "$BODY" "$SIG" "$ID")" 202
check "same delivery again" "$(send "$BODY" "$SIG" "$ID")" 200
check "body changed after signing" "$(send "${BODY/1347/1348}" "$SIG" "$ID-b")" 401
check "no signature" "$(send "$BODY" "" "$ID-c")" 401
check "signed but not JSON" "$(send "not json" "$(sign "not json")" "$ID-d")" 400
exit $FAILEDchmod +x test-webhook.sh GITHUB_WEBHOOK_SECRET="It's a test secret" ./test-webhook.sh http://localhost:8080/webhooks/github
ok valid delivery (202) ok same delivery again (200) ok body changed after signing (401) ok no signature (401) ok signed but not JSON (400)
The server logs issues opened octocat/Hello-World once, after the first response. A FAIL line names the check that broke; the mistakes table below lists what usually causes each one.
Start it without GITHUB_WEBHOOK_SECRET and Spring refuses to start with Could not resolve placeholder 'GITHUB_WEBHOOK_SECRET'. That's intended.
Receive real GitHub deliveries on localhost
GitHub won't send webhooks to localhost. Give it a HookWatcher endpoint instead, and let hwcli deliver each capture to your server byte for byte:
- Create a free HookWatcher account (or sign in) and create an endpoint; hwcli works with the endpoints in your account. Its URL looks like
https://hookwatcher.com/<endpoint-id>. - In the repository on GitHub, open Settings → Webhooks → Add webhook. Use the endpoint URL as the payload URL,
application/jsonas the content type, and the same secret your server reads fromGITHUB_WEBHOOK_SECRET. - Run hwcli on your machine.
--include-sensitivematters here: without it, signature headers are left out of local deliveries and every request fails with401.
hwcli login hwcli listen <endpoint-id> --to http://localhost:8080/webhooks/github --include-sensitive
GitHub's ping arrives as soon as the webhook is saved, and your handler answers 202. To send a capture again, run hwcli replay <request-id>: it keeps the original X-GitHub-Delivery, so your handler should answer 200 duplicate. That's your deduplication tested with a real delivery. GitHub's signature has no timestamp, so replayed bytes still verify.
Common mistakes in Java webhook handlers
| Symptom | Cause | Fix |
|---|---|---|
| Every request is 401, but the secret is right | The body is bound to a DTO or String, or a filter read the stream first | Bind @RequestBody byte[]; don't consume the body in filters for this path |
| 403 Forbidden on every POST | Spring Security's CSRF protection is on | Exclude the path with csrf.ignoringRequestMatchers("/webhooks/**") and permit it; the signature check is the authentication |
Imports of com.fasterxml.jackson don't resolve | Spring Boot 4 uses Jackson 3, in the tools.jackson packages | Use tools.jackson.databind on Boot 4; on Boot 3 use ObjectMapper and catch IOException |
| Events processed before the response | @Async without @EnableAsync, or called from the same class (no proxy) | Enable async and call the method on another bean, as above |
| Duplicates slip through with several instances | Each JVM has its own set of IDs | Use a unique database key or Redis SET NX (see the FAQ) |
| GitHub shows "Timed out" | Work runs on the request thread | Queue it and answer 202 |
See the exact bytes your controller must verify
Frequently asked questions
Can I use this without Spring?
Yes. GitHubSignature needs only javax.crypto and java.security. Read the request body as bytes in your framework (a JAX-RS resource method taking byte[], HttpServletRequest.getInputStream().readAllBytes()) and pass them in before parsing.
Why HexFormat instead of a hex helper?
java.util.HexFormat is in the JDK since Java 17 and formats lowercase hex, which is what GitHub sends. Older code often has hand-written loops that drop leading zeros.
Does this work on Spring Boot 3?
The signature class and controller logic do. Change the starter to spring-boot-starter-web, and use Jackson 2's ObjectMapper with IOException instead of JsonMapper and JacksonException.
Is an in-memory set of delivery IDs enough in production?
No. It's empty after a restart and separate in every process or server. Store processed IDs where all instances see them: a database table with a unique key on the delivery ID (insert, and treat a unique-constraint error as a duplicate) or Redis SET key value NX EX 259200. Three days covers GitHub's redelivery window.
Sources
- Java SE 25 API: MessageDigest.isEqual
- Spring Framework: @RequestBody
- Spring Framework: @RequestHeader
- Spring Boot reference documentation
- GitHub Docs: Validating webhook deliveries
More on GitHub webhooks
Headers, form-encoded payloads and delivery errors: GitHub webhook testing.