Verify webhook signatures in a Drupal controller
A payment provider, a Git host or a CRM tells me it will POST to my site whenever something happens. The first version of that endpoint I write is always the same: a route open to everyone, a controller that decodes the JSON and trusts it. That is an unauthenticated write path into my site, and anyone who guesses the URL can forge events. Here is the small pattern I use instead: verify an HMAC signature before touching the payload.
The route
The endpoint has to be reachable by anonymous callers, because the sender has no Drupal session. The access check therefore moves from Drupal's permission system into the controller itself. I restrict the route to POST so a stray GET never reaches the handler.
mymodule.webhook:
path: '/webhook/incoming'
defaults:
_controller: '\Drupal\mymodule\Controller\WebhookController::receive'
methods: [POST]
requirements:
_access: 'TRUE'
The controller
Most providers send a hex-encoded HMAC-SHA256 of the raw request body in a header. The word raw matters: if I decode and re-encode the JSON first, whitespace and key order can change and the hashes will never match. Request::getContent() gives me the untouched bytes. I compute the expected signature with hash_hmac() and compare with hash_equals(), which is timing-safe, unlike ===. Only then do I look at the JSON, using json_validate() (PHP 8.3+) as a cheap check that doesn't build the decoded structure.
<?php
namespace Drupal\mymodule\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Site\Settings;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Receives signed webhooks from an external service.
*/
class WebhookController extends ControllerBase {
public function receive(Request $request): Response {
$secret = Settings::get('mymodule_webhook_secret');
if (!is_string($secret) || $secret === '') {
// Fail closed: no secret configured means no webhooks accepted.
return new JsonResponse(['error' => 'Not configured'], 503);
}
$body = $request->getContent();
$given = (string) $request->headers->get('X-Signature', '');
$expected = hash_hmac('sha256', $body, $secret);
if (!hash_equals($expected, $given)) {
return new JsonResponse(['error' => 'Bad signature'], 401);
}
if (!json_validate($body)) {
return new JsonResponse(['error' => 'Invalid JSON'], 400);
}
$event = json_decode($body, TRUE);
// Hand off to a queue here; acknowledge fast.
return new JsonResponse(['received' => TRUE], 202);
}
}
The secret lives in settings.php ($settings['mymodule_webhook_secret'] = getenv('WEBHOOK_SECRET');), not in config, so it never lands in an exported YAML file or a Git repository.
Why each line is there
- Fail closed. If the secret is missing, an empty string would make
hash_hmac()produce a predictable signature that anyone could compute. Returning 503 avoids that. - Cast the header to string.
hash_equals()throws a TypeError for non-string input, and a missing header would benull. - Signature before parsing. Unauthenticated callers never get to exercise my JSON handling.
- 202, not 200. I acknowledge receipt and do the real work elsewhere, so the sender doesn't time out and retry.
I traced this by hand rather than running it, so check your provider's exact header name and encoding. Some prefix the signature with sha256=, and some sign a timestamp together with the body.
The gotcha is replay. A valid signature stays valid forever, so an attacker who captures one request can resend it. If your provider includes a timestamp in the signed material, reject anything older than a few minutes. If it doesn't, make the handler idempotent by storing event IDs. For anything heavier than a few lines of work, push the decoded event onto a queue and return immediately.