|
1 | 1 | package io.mailtrap.examples.webhooks; |
2 | 2 |
|
| 3 | +import com.sun.net.httpserver.HttpServer; |
3 | 4 | import io.mailtrap.webhooks.WebhookSignatures; |
4 | 5 |
|
5 | | -import javax.crypto.Mac; |
6 | | -import javax.crypto.spec.SecretKeySpec; |
| 6 | +import java.io.IOException; |
| 7 | +import java.io.InputStream; |
| 8 | +import java.net.InetSocketAddress; |
7 | 9 | import java.nio.charset.StandardCharsets; |
8 | | -import java.util.HexFormat; |
9 | 10 |
|
10 | 11 | public class WebhookSignatureExample { |
11 | 12 |
|
12 | | - public static void main(final String[] args) throws Exception { |
13 | | - // --- Direct verification (e.g. for unit tests or custom routers) ---- |
14 | | - final String payload = "{\"event\":\"delivery\",\"message_id\":\"abc-123\"}"; |
15 | | - final String signingSecret = "8d9a3c0e7f5b2d4a6c1e9f8b3a7d5c2e"; |
| 13 | + public static void main(final String[] args) throws IOException { |
| 14 | + final String signingSecret = System.getenv("MAILTRAP_WEBHOOK_SIGNING_SECRET"); |
16 | 15 |
|
17 | | - final Mac mac = Mac.getInstance("HmacSHA256"); |
18 | | - mac.init(new SecretKeySpec(signingSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); |
19 | | - final String signature = HexFormat.of().formatHex( |
20 | | - mac.doFinal(payload.getBytes(StandardCharsets.UTF_8))); |
| 16 | + final HttpServer server = HttpServer.create(new InetSocketAddress(9292), 0); |
| 17 | + server.createContext("/webhooks/mailtrap", exchange -> { |
| 18 | + // Use the raw request body — parsing and re-serializing the JSON may |
| 19 | + // reorder keys or alter whitespace and invalidate the signature. |
| 20 | + final String payload; |
| 21 | + try (InputStream body = exchange.getRequestBody()) { |
| 22 | + payload = new String(body.readAllBytes(), StandardCharsets.UTF_8); |
| 23 | + } |
| 24 | + final String signature = exchange.getRequestHeaders().getFirst("Mailtrap-Signature"); |
21 | 25 |
|
22 | | - if (!WebhookSignatures.verify(payload, signature, signingSecret)) { |
23 | | - throw new IllegalStateException("Signature verification failed!"); |
24 | | - } |
| 26 | + if (!WebhookSignatures.verify(payload, signature, signingSecret)) { |
| 27 | + exchange.sendResponseHeaders(401, -1); |
| 28 | + exchange.close(); |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + exchange.sendResponseHeaders(200, -1); |
| 33 | + exchange.close(); |
| 34 | + }); |
| 35 | + server.start(); |
25 | 36 | } |
26 | 37 | } |
0 commit comments