How do webhook security mechanisms verify the authenticity of incoming HTTP notifications from external systems?
Answer
Basics: A webhook is an inbound HTTP call. Anyone who knows the URL can post to it, so the receiver must verify the sender. In an HMAC scheme, the sender signs the body with a secret key and sends the result, for example in X-Signature. The receiver does the same calculation and compares.
How it works:
- Share a secret out of band and store it securely (Named Credential, protected Custom Metadata, or a secrets manager).
- The sender computes HMAC-SHA256 of the raw body, often with a timestamp, and sends it in a header.
- The receiver reads the raw body bytes (not a re-serialised object), recomputes the HMAC, and compares.
- Reject mismatches with 401 or 403 and do no work.
- Check the timestamp and a unique delivery ID to stop replays.
Advanced / deep dive: In Salesforce, an @RestResource class or an Experience Cloud/Site endpoint can receive webhooks. Use RestContext.request.requestBody so you sign exactly what was sent. Compare the strings carefully. Apex has no built-in constant-time compare, so keep the compare simple and rate-limit failures (verify whether Crypto.verifyHmac is available in your API version for a safer check). Guest user endpoints need minimal permissions, since the guest profile is public. Add IP allowlists if the sender publishes ranges, use HTTPS only, and respond fast with a 2xx while processing asynchronously, for example by publishing a platform event.
Code / config example:
@RestResource(urlMapping='/webhook/v1/*')
global with sharing class WebhookReceiver {
global {
RestContext.request;
req.headers.get();
Crypto.generateMac(, req.requestBody, Blob.valueOf(Secrets__mdt.getInstance().Key__c));
EncodingUtil.convertToHex(mac);
(sent == || sent != expected) {
RestContext.response.statusCode = ;
;
}
EventBus.publish( (Body__c = req.requestBody.toString()));
RestContext.response.statusCode = ;
}
}