Accept inbound webhooks (Stripe, GitHub, Slack, partner) and verify HMAC signatures in Apex REST — Crypto.verifyHMac platform verification, secret in Protected Custom Metadata, replay-window rejection. NOT for designing the receiver end to end — Sites routing, guest-user access, idempotency, the 5-second response window — use integration/webhook-inbound-patterns. NOT for signing a webhook Salesforce sends out — use integration/outbound-webhook-from-salesforce.
An inbound webhook is an HTTP POST from a third party that Salesforce did not
initiate and cannot authenticate by session. When the endpoint is exposed through
a public Salesforce Site, the signature check is the entire authentication
boundary — there is no user, no token, and no network control in front of it.
Three properties have to hold, and each fails independently:
Property
Established by
Fails when
Authenticity — the sender holds the shared secret
HMAC over the payload
Secret is wrong, or the wrong encoding of the right secret
Integrity — the bytes were not altered in transit
HMAC over the raw body
The body was parsed and re-serialised before hashing
Freshness — this is not a replay of an earlier valid request
Timestamp tolerance + idempotency key
Neither is implemented — the signature alone never establishes this
Most broken webhook endpoints have the first two and not the third.
Scope. This skill owns the verification step: which Apex crypto method to
call, over which bytes, against which secret, and what to reject. Designing the
receiver end to end — Sites routing, guest-user access model, the idempotency
schema, the response-window budget — belongs to
integration/webhook-inbound-patterns. Those subjects appear below only as far as
they change the verification decision (for example: on a public Site the signature
is the only gate, which raises the stakes on every gotcha here). Signing a webhook
Salesforce sends is integration/outbound-webhook-from-salesforce.
Before Starting
Identify the signature scheme. HMAC (shared secret) or asymmetric
(RSA/ECDSA against a published public key)? They need different Apex methods
and different secret storage. Do not assume HMAC.
Get the exact header name, value format, and signed payload. Not every
provider signs the body alone — Stripe signs "{timestamp}.{body}". Getting
this wrong produces 100% verification failure that looks like a key problem.
Decide how the request reaches Apex./services/apexrest/* requires an
authenticated session, which a webhook does not have. Either the provider
obtains a token (Connected App, client credentials flow) or you expose the class
through a Salesforce Site guest user. Pick before you write the class.
Choose where the secret lives. Protected Custom Metadata, read via
getAll(). Not a literal, not a Custom Setting, not a Named Credential (which
is for outbound).
Crypto.generateMac produces a MAC and is correct for building a signature (in
tests, or when calling out). It is the wrong tool for checking one, because it
forces you to write the comparison yourself — and String.equals short-circuits
on the first differing character. Both Stripe and GitHub explicitly tell
integrators to compare signatures in constant time.
What the Apex Reference Guide does and does not say. Its verifyHMac entry
documents the signature, the four valid algorithm names, the 4 KB key cap, the
Base64 symmetry rule, and the Boolean return. It makes no timing claim. So
verifyHMac is the recommended method here because it keeps the comparison out
of your code entirely, not because Salesforce documents it as constant-time —
that property is undocumented, and this skill does not assert it. Detail in
references/gotchas.md, Gotcha 4.
with the provider's public certificate stored in Setup → Certificate and Key
Management, so rotation is a Setup change rather than a deploy.
The Base64 symmetry rule
"You may supply a private key that has been encoded using Base64 encoding.
However if you do, then you must also supply the Base64-encoded private key when
verifying the MAC using the verifyHMac method."
— Apex Reference Guide, Crypto.generateMac
Record in a comment which form the provider uses. Stripe's whsec_... is an
opaque ASCII string used raw; some providers issue a Base64 blob that must be
decoded first.
Raw body only
RestRequest.requestBody is a Blob — the exact bytes the sender hashed.
JSON.serialize(JSON.deserializeUntyped(...)) reorders keys, strips whitespace,
and normalises numbers, so a MAC computed over the round trip never matches. Verify
first; parse second.
Headers are case-insensitive; Apex maps are not
RestRequest.headers is a Map<String, String> with exact-match lookup. Proxies
and provider clients normalise header casing differently, so
headers.get('Stripe-Signature') can return null in production while working in
a test that used the same spelling. Always look up case-insensitively.
Size ceiling
"The maximum request or response size is 6 MB for synchronous Apex or 12 MB for
asynchronous Apex." A provider posting near that ceiling has outgrown the webhook
shape; move to notification-plus-pull.
Common Patterns
Pattern A — verify, stage, return 200, process async
The default. The resource verifies, upserts the raw event against an External Id,
enqueues a Queueable, and returns. Providers time out in single-digit seconds and
retry on timeout; anything slower turns one event into repeated deliveries. Full
implementation in references/examples.md, Example 2.
Pattern B — replay window before HMAC
If the provider signs a timestamp, check it first. A replay flood then costs a
Long comparison rather than a crypto operation. Stripe's libraries "have a
default tolerance of 5 minutes between the timestamp and the current time," and
Stripe warns against a tolerance of 0 because it disables the recency check
entirely.
Pattern C — accept multiple signatures during rotation
Stripe emits one signature per active secret while a secret roll is in flight
(previous secret active for up to 24 hours), so a verifier that loops over every
v1= value rides the rotation with no downtime. Where the provider does not do
this, hold Secret__c and Previous_Secret__c on the metadata record and try
both, removing the old value in a separate, dated change.
Pattern D — layer IP allowlisting where the provider publishes ranges
Stripe publishes its webhook source IPs and recommends allowlisting them in
addition to signature verification. This is defence in depth, not a replacement:
IP ranges change, and an allowlist alone proves nothing about payload integrity.
Crypto.verify(alg, data, sig, certDevName) with the cert in Certificate and Key Management
Provider can send a bearer token
Connected App + OAuth 2.0 client credentials flow, and keep the signature check
Provider cannot authenticate at all
Public Site + guest-user Apex class access; the HMAC check is the only gate
Provider signs a derived payload
Reconstruct the derivation from the raw body string, never from a re-serialised object
Payload approaches 6 MB
Notification-plus-pull: the event carries an id, Salesforce fetches the body
Provider offers several signature schemes
Pin one in code; never let the sender choose the algorithm
Recommended Workflow
Read the provider's signature documentation and write down four things:
header name, value grammar, exactly which bytes are signed, and the algorithm.
Note whether the secret is used raw or Base64-decoded.
Store the secret as protected Custom Metadata and expose it through a small
accessor using getAll() so it costs no SOQL query. Never a literal, never a
Custom Setting.
Write the resource in the fixed order: read raw body → read signature
header case-insensitively → reject if absent or malformed → reject if the
timestamp is outside tolerance → Crypto.verifyHMac → only then deserialise.
Make it idempotent. Upsert against the provider's event id on an External
Id, Unique field, and act only when Database.UpsertResult indicates a new row.
Return 2xx immediately and move all processing to a Queueable or a platform
event subscriber. No callouts, no email, no Flow inside the handler.
Expose the endpoint deliberately — Connected App with client credentials, or
Site guest user with the narrowest possible object access — and record which
shape you chose and why.
Test the negatives: tampered body with a captured signature, stale
timestamp with a valid signature, missing header, and a header supplied in
different casing from the handler's spelling.
Review Checklist
Crypto.verifyHMac used, not generateMac plus an equality comparison
The Blob hashed is req.requestBody, untouched — no JSON.serialize between
Signature header read case-insensitively
Signature scheme matched exactly (v1), not by prefix
Timestamp tolerance enforced, and checked before the HMAC
Idempotency via External Id, Unique upsert on the provider's event id
Secret in protected Custom Metadata; comment records raw vs Base64 form
Rejection responses are terse and identical for every failure reason
Raw body, signature header, and secret never logged
Handler returns 2xx before any processing; work is enqueued
Rotation path accepts both current and previous secret
Endpoint exposure (Connected App or Site guest user) documented, with guest
user object access minimised
Negative tests: tampered body, stale timestamp, missing header, odd casing
Salesforce-Specific Gotchas
Full detail in references/gotchas.md.
The Base64 rule on privateKey is bidirectional — encode on both sides or
neither. Key cap is 4 KB.
Apex map keys are case-sensitive; HTTP header names are not. Intermittent
401s in production, green tests locally.
Re-serialising the body guarantees 100% verification failure — which
usually gets "fixed" by deleting the check.
generateMac + equals is a hand-rolled comparison; verifyHMac is not.
A valid signature is not a fresh request. Replay window plus idempotency.
Slow handlers cause retries, not patience. Verify, stage, 200, enqueue.
Apex REST needs a session — webhooks have none. Connected App or Site.
Not every provider uses HMAC. Asymmetric schemes need Crypto.verify.
Logging the payload logs the data, and logging the signature makes a
captured request replayable from your log store.
Accepting any vN scheme is a downgrade attack. Pin v1.
Rotation without dual acceptance is a silent outage of 401s.
Output Artifacts
Artifact
Description
Provider signature contract note
Header name, value grammar, signed-bytes definition, algorithm, secret encoding form, and the provider doc URL it came from
Apex REST resource
Verify → stage → 2xx → enqueue, with a case-insensitive header lookup and terse rejections
Secret metadata
Protected Webhook_Secret__mdt record plus the accessor class, with a rotation note naming when the previous value may be removed
Staging object
External Id, Unique on the provider event id, restricted to the integration's permission set, with a retention policy
Negative test class
Tampered body, stale timestamp, missing header, alternate header casing
Exposure decision record
Connected App vs Site guest user, with the guest user's granted object access enumerated
Related Skills
integration/webhook-inbound-patterns — the receiver design this skill sits
inside: Sites routing, guest-user access model, idempotency schema, and the
response-window budget. Read it first if you are building the endpoint rather
than fixing the signature check.
integration/outbound-webhook-from-salesforce — signing a webhook Salesforce
sends, which is the mirror image of this problem
apex/apex-rest-services — the @RestResource surface itself: URL mapping
rules, supported HTTP methods, and response handling
security/guest-user-security — hardening the Site guest user that a public
webhook endpoint necessarily exposes
integration/retry-and-backoff-patterns — the provider side of at-least-once
delivery, and what your 2xx does and does not promise
1---2name: webhook-signature-verification3description: "Accept inbound webhooks (Stripe, GitHub, Slack, partner) and verify HMAC signatures in Apex REST — Crypto.verifyHMac platform verification, secret in Protected Custom Metadata, replay-window rejection. NOT for designing the receiver end to end — Sites routing, guest-user access, idempotency, the 5-second response window — use integration/webhook-inbound-patterns. NOT for signing a webhook Salesforce sends out — use integration/outbound-webhook-from-salesforce."4category: integration5salesforce-version: "Spring '25+"6well-architected-pillars:7 - Security8 - Reliability9triggers:10 - "webhook hmac verification apex"11 - "stripe webhook salesforce"12 - "verify signature inbound callout"13 - "hmac sha256 apex"14tags:15 - webhook16 - hmac17 - signature18 - apex-rest19inputs:20 - "webhook provider HMAC spec"21 - "shared secret location"22outputs:23 - "@RestResource endpoint with signature verification"24dependencies: []25version: 1.0.126author: Pranav Nagrecha27updated: 2026-08-1428metadata:29 source: https://skillmd.com/skills/pranavnagrecha/webhook-signature-verification30---313233# Webhook Signature Verification3435An inbound webhook is an HTTP POST from a third party that Salesforce did not36initiate and cannot authenticate by session. When the endpoint is exposed through37a public Salesforce Site, the signature check is the *entire* authentication38boundary — there is no user, no token, and no network control in front of it.3940Three properties have to hold, and each fails independently:4142| Property | Established by | Fails when |43|---|---|---|44| **Authenticity** — the sender holds the shared secret | HMAC over the payload | Secret is wrong, or the wrong encoding of the right secret |45| **Integrity** — the bytes were not altered in transit | HMAC over the **raw** body | The body was parsed and re-serialised before hashing |46| **Freshness** — this is not a replay of an earlier valid request | Timestamp tolerance + idempotency key | Neither is implemented — the signature alone never establishes this |4748Most broken webhook endpoints have the first two and not the third.4950**Scope.** This skill owns the *verification* step: which Apex crypto method to51call, over which bytes, against which secret, and what to reject. Designing the52receiver end to end — Sites routing, guest-user access model, the idempotency53schema, the response-window budget — belongs to54`integration/webhook-inbound-patterns`. Those subjects appear below only as far as55they change the verification decision (for example: on a public Site the signature56is the only gate, which raises the stakes on every gotcha here). Signing a webhook57Salesforce *sends* is `integration/outbound-webhook-from-salesforce`.5859---6061## Before Starting62631. **Identify the signature scheme.** HMAC (shared secret) or asymmetric64 (RSA/ECDSA against a published public key)? They need different Apex methods65 and different secret storage. Do not assume HMAC.66672. **Get the exact header name, value format, and signed payload.** Not every68 provider signs the body alone — Stripe signs `"{timestamp}.{body}"`. Getting69 this wrong produces 100% verification failure that looks like a key problem.70713. **Decide how the request reaches Apex.** `/services/apexrest/*` requires an72 authenticated session, which a webhook does not have. Either the provider73 obtains a token (Connected App, client credentials flow) or you expose the class74 through a Salesforce Site guest user. Pick before you write the class.75764. **Choose where the secret lives.** Protected Custom Metadata, read via77 `getAll()`. Not a literal, not a Custom Setting, not a Named Credential (which78 is for outbound).7980---8182## Core Concepts8384### `Crypto.verifyHMac` is the method you want8586```apex87public static Boolean Crypto.verifyHMac(88 String algorithmName, // hmacMD5 | hmacSHA1 | hmacSHA256 | hmacSHA51289 Blob data,90 Blob privateKey, // max 4 KB91 Blob macToVerify92)93```9495`Crypto.generateMac` produces a MAC and is correct for *building* a signature (in96tests, or when calling out). It is the wrong tool for checking one, because it97forces you to write the comparison yourself — and `String.equals` short-circuits98on the first differing character. Both Stripe and GitHub explicitly tell99integrators to compare signatures in constant time.100101**What the Apex Reference Guide does and does not say.** Its `verifyHMac` entry102documents the signature, the four valid algorithm names, the 4 KB key cap, the103Base64 symmetry rule, and the Boolean return. It makes **no timing claim**. So104`verifyHMac` is the recommended method here because it keeps the comparison out105of your code entirely, not because Salesforce documents it as constant-time —106that property is undocumented, and this skill does not assert it. Detail in107[`references/gotchas.md`](references/gotchas.md), Gotcha 4.108109For asymmetric providers:110111```apex112public static Boolean Crypto.verify(String algorithmName, Blob data,113 Blob signature, String certDevName)114```115116with the provider's public certificate stored in **Setup → Certificate and Key117Management**, so rotation is a Setup change rather than a deploy.118119### The Base64 symmetry rule120121> "You may supply a private key that has been encoded using Base64 encoding.122> However if you do, then you must also supply the Base64-encoded private key when123> verifying the MAC using the `verifyHMac` method."124> — Apex Reference Guide, `Crypto.generateMac`125126Record in a comment which form the provider uses. Stripe's `whsec_...` is an127opaque ASCII string used raw; some providers issue a Base64 blob that must be128decoded first.129130### Raw body only131132`RestRequest.requestBody` is a `Blob` — the exact bytes the sender hashed.133`JSON.serialize(JSON.deserializeUntyped(...))` reorders keys, strips whitespace,134and normalises numbers, so a MAC computed over the round trip never matches. Verify135first; parse second.136137### Headers are case-insensitive; Apex maps are not138139`RestRequest.headers` is a `Map<String, String>` with exact-match lookup. Proxies140and provider clients normalise header casing differently, so141`headers.get('Stripe-Signature')` can return `null` in production while working in142a test that used the same spelling. Always look up case-insensitively.143144### Size ceiling145146"The maximum request or response size is 6 MB for synchronous Apex or 12 MB for147asynchronous Apex." A provider posting near that ceiling has outgrown the webhook148shape; move to notification-plus-pull.149150---151152## Common Patterns153154### Pattern A — verify, stage, return 200, process async155156The default. The resource verifies, upserts the raw event against an External Id,157enqueues a Queueable, and returns. Providers time out in single-digit seconds and158retry on timeout; anything slower turns one event into repeated deliveries. Full159implementation in [`references/examples.md`](references/examples.md), Example 2.160161### Pattern B — replay window before HMAC162163If the provider signs a timestamp, check it first. A replay flood then costs a164`Long` comparison rather than a crypto operation. Stripe's libraries "have a165default tolerance of 5 minutes between the timestamp and the current time," and166Stripe warns against a tolerance of `0` because it disables the recency check167entirely.168169### Pattern C — accept multiple signatures during rotation170171Stripe emits one signature per active secret while a secret roll is in flight172(previous secret active for up to 24 hours), so a verifier that loops over every173`v1=` value rides the rotation with no downtime. Where the provider does not do174this, hold `Secret__c` and `Previous_Secret__c` on the metadata record and try175both, removing the old value in a separate, dated change.176177### Pattern D — layer IP allowlisting where the provider publishes ranges178179Stripe publishes its webhook source IPs and recommends allowlisting them in180addition to signature verification. This is defence in depth, not a replacement:181IP ranges change, and an allowlist alone proves nothing about payload integrity.182183---184185## Decision Guidance186187| Situation | Approach |188|---|---|189| Provider issues a shared secret | `Crypto.verifyHMac('hmacSHA256', rawBody, secret, mac)` |190| Provider publishes a public certificate / JWKS | `Crypto.verify(alg, data, sig, certDevName)` with the cert in Certificate and Key Management |191| Provider can send a bearer token | Connected App + OAuth 2.0 client credentials flow, **and** keep the signature check |192| Provider cannot authenticate at all | Public Site + guest-user Apex class access; the HMAC check is the only gate |193| Provider signs a derived payload | Reconstruct the derivation from the raw body string, never from a re-serialised object |194| Payload approaches 6 MB | Notification-plus-pull: the event carries an id, Salesforce fetches the body |195| Provider offers several signature schemes | Pin one in code; never let the sender choose the algorithm |196197---198199## Recommended Workflow2002011. **Read the provider's signature documentation and write down four things**:202 header name, value grammar, exactly which bytes are signed, and the algorithm.203 Note whether the secret is used raw or Base64-decoded.2042. **Store the secret as protected Custom Metadata** and expose it through a small205 accessor using `getAll()` so it costs no SOQL query. Never a literal, never a206 Custom Setting.2073. **Write the resource in the fixed order**: read raw body → read signature208 header case-insensitively → reject if absent or malformed → reject if the209 timestamp is outside tolerance → `Crypto.verifyHMac` → *only then* deserialise.2104. **Make it idempotent.** Upsert against the provider's event id on an External211 Id, Unique field, and act only when `Database.UpsertResult` indicates a new row.2125. **Return 2xx immediately** and move all processing to a Queueable or a platform213 event subscriber. No callouts, no email, no Flow inside the handler.2146. **Expose the endpoint deliberately** — Connected App with client credentials, or215 Site guest user with the narrowest possible object access — and record which216 shape you chose and why.2177. **Test the negatives**: tampered body with a captured signature, stale218 timestamp with a valid signature, missing header, and a header supplied in219 different casing from the handler's spelling.220221---222223## Review Checklist224225- [ ] `Crypto.verifyHMac` used, not `generateMac` plus an equality comparison226- [ ] The `Blob` hashed is `req.requestBody`, untouched — no `JSON.serialize` between227- [ ] Signature header read case-insensitively228- [ ] Signature scheme matched exactly (`v1`), not by prefix229- [ ] Timestamp tolerance enforced, and checked before the HMAC230- [ ] Idempotency via External Id, Unique upsert on the provider's event id231- [ ] Secret in protected Custom Metadata; comment records raw vs Base64 form232- [ ] Rejection responses are terse and identical for every failure reason233- [ ] Raw body, signature header, and secret never logged234- [ ] Handler returns 2xx before any processing; work is enqueued235- [ ] Rotation path accepts both current and previous secret236- [ ] Endpoint exposure (Connected App or Site guest user) documented, with guest237 user object access minimised238- [ ] Negative tests: tampered body, stale timestamp, missing header, odd casing239240---241242## Salesforce-Specific Gotchas243244Full detail in [`references/gotchas.md`](references/gotchas.md).2452461. **The Base64 rule on `privateKey` is bidirectional** — encode on both sides or247 neither. Key cap is 4 KB.2482. **Apex map keys are case-sensitive; HTTP header names are not.** Intermittent249 401s in production, green tests locally.2503. **Re-serialising the body guarantees 100% verification failure** — which251 usually gets "fixed" by deleting the check.2524. **`generateMac` + `equals` is a hand-rolled comparison**; `verifyHMac` is not.2535. **A valid signature is not a fresh request.** Replay window plus idempotency.2546. **Slow handlers cause retries, not patience.** Verify, stage, 200, enqueue.2557. **Apex REST needs a session** — webhooks have none. Connected App or Site.2568. **Not every provider uses HMAC.** Asymmetric schemes need `Crypto.verify`.2579. **Logging the payload logs the data**, and logging the signature makes a258 captured request replayable from your log store.25910. **Accepting any `vN` scheme is a downgrade attack.** Pin `v1`.26011. **Rotation without dual acceptance is a silent outage** of 401s.261262---263264## Output Artifacts265266| Artifact | Description |267|---|---|268| Provider signature contract note | Header name, value grammar, signed-bytes definition, algorithm, secret encoding form, and the provider doc URL it came from |269| Apex REST resource | Verify → stage → 2xx → enqueue, with a case-insensitive header lookup and terse rejections |270| Secret metadata | Protected `Webhook_Secret__mdt` record plus the accessor class, with a rotation note naming when the previous value may be removed |271| Staging object | External Id, Unique on the provider event id, restricted to the integration's permission set, with a retention policy |272| Negative test class | Tampered body, stale timestamp, missing header, alternate header casing |273| Exposure decision record | Connected App vs Site guest user, with the guest user's granted object access enumerated |274275---276277## Related Skills278279- `integration/webhook-inbound-patterns` — the receiver design this skill sits280 inside: Sites routing, guest-user access model, idempotency schema, and the281 response-window budget. Read it first if you are building the endpoint rather282 than fixing the signature check.283- `integration/outbound-webhook-from-salesforce` — signing a webhook Salesforce284 sends, which is the mirror image of this problem285- `apex/apex-rest-services` — the `@RestResource` surface itself: URL mapping286 rules, supported HTTP methods, and response handling287- `security/guest-user-security` — hardening the Site guest user that a public288 webhook endpoint necessarily exposes289- `integration/retry-and-backoff-patterns` — the provider side of at-least-once290 delivery, and what your 2xx does and does not promise
Run npx get-skill add pranavnagrecha/webhook-signature-verification in your terminal (requires Node.js), paste this page's agent-chat prompt into Claude, Cursor, or any MCP-connected agent, or download the SKILL.md file and copy it into your agent's skills directory.
Accept inbound webhooks (Stripe, GitHub, Slack, partner) and verify HMAC signatures in Apex REST — Crypto.verifyHMac platform verification, secret in Protected Custom Metadata, replay-window rejection. NOT for designing the receiver end to end — Sites routing, guest-user access, idempotency, the 5-second response window — use integration/webhook-inbound-patterns. NOT for signing a webhook Salesforce sends out — use integration/outbound-webhook-from-salesforce. It is listed under Security on SkillMD.
This skill has not completed SkillMD's automated safety review yet. Independent scanners report: SkillSpector: PASS, Skill Scanner: PASS. Capability flags: executes scripts, reads secrets. SkillMD never runs a skill's scripts for you; review the SKILL.md before installing.
This skill is tagged as working with Claude Code, Claude.ai, OpenAI Codex. SKILL.md is an open format, so most agents that read a skills directory can load it too.
Yes. Installing skills from SkillMD is free, and the skill stays under its author's original license.
PranavNagrecha (@pranavnagrecha) published this skill. Their other Agent Skills are listed on their SkillMD profile.