WebhookAgent
HMAC vs JWT for Webhooks: Which to Use, and the One Question That Decides It

HMAC vs JWT for Webhooks: Which to Use, and the One Question That Decides It

May 8, 2026 32 min read

TL;DR

  • HMAC vs JWT for webhooks, short answer: for most webhooks, sign the message ID, a timestamp and the raw body with HMAC-SHA256 and reject anything older than about five minutes. Stripe, Slack and Zoom all sign a timestamp with the body, and the Standard Webhooks spec adds the message ID.
  • Pick a JWT, signed with an asymmetric key (ES256, EdDSA or RS256), when receivers cannot be trusted to guard a shared secret, or when you need claims like audience and expiry. Then make sure the token carries a hash of the body, the way Plaid and FusionAuth do it.
  • The comparison is slightly off from the start: a JWT signed with HS256 is an HMAC. The real choice is about what the signature covers and who holds the key.
  • Every provider detail below was checked against its own documentation in November 2026, and every code sample was run on our machine.

If you are deciding between HMAC vs JWT for webhooks, here is the answer most teams need: use an HMAC-SHA256 signature over the message ID, a timestamp and the exact bytes of the request body, compare it in constant time, and drop deliveries older than about five minutes. Reach for a JWT when the receiver should verify with a public key instead of a shared secret, or when the request has to carry signed claims about who it is for. If you do use a JWT, insist that it also signs a hash of the body. The rest of this guide explains why, with the details that the usual comparison tables leave out.

We started with a small experiment. We built a webhook body for an invoice of 5,000, signed a JWT for it with a shared secret, and attached the token the way many bearer-token webhooks do, in a header next to the body. Then we changed the amount in the body to 50,000. The token still decoded cleanly: right issuer, right audience, not expired. Our library, PyJWT 2.15.1, had nothing to object to, because nothing in the token said anything about the body. Only a second check, comparing a SHA-256 hash of the body against a claim inside the token, caught the change.

That small result is the whole argument of this piece in miniature. "HMAC or JWT" sounds like a choice between two kinds of lock. In practice it is a choice about which part of the message gets locked, and who is trusted with the key. Teams that frame it as a format question tend to pick a format and stop. Teams that frame it as a coverage question tend to ship receivers that hold up. What follows walks through the mechanism, the providers that use each approach today, the attacks that have actually broken JWT libraries, numbers we measured ourselves, and a decision framework you can apply in an afternoon.

Two things that are not the same kind of thing

Start with the literal definitions, because the confusion begins there. HMAC, defined in RFC 2104 back in February 1997, is a construction: take a secret key and a message, run them through a hash function such as SHA-256 in a specific two-pass way, and get a short tag. Anyone holding the same key can recompute the tag and compare. If one byte of the message changed, the tags will not match. HMAC is a primitive. It has no opinion about headers, claims or expiry.

A JSON Web Token, defined in RFC 7519 in May 2015, is a format. It is three base64url-encoded parts joined by dots: a header naming the algorithm, a set of claims (issuer, audience, issued-at, expiry and anything else you add), and a signature produced under JSON Web Signature, RFC 7515. The signature algorithm is a field in the header. Set it to HS256 and the signature is literally HMAC with SHA-256. Set it to RS256, ES256 or EdDSA and it is an RSA, ECDSA or Edwards-curve (typically Ed25519) signature, made with a private key and checked with a public one.

So a JWT signed with HS256 is an HMAC wrapped in a standard envelope. Comparing "HMAC vs JWT" is a bit like comparing a wax seal with an envelope. It helps to hold onto that picture for the rest of this guide. A webhook signature works like a wax seal pressed over the fold of a letter: if the seal is intact, nobody opened the letter or swapped its pages since it was sealed. HMAC is the seal made with a signet ring, where sender and receiver each own an identical copy of the ring. Asymmetric signatures are a notary's seal, where only the notary has the stamp and anyone can check the impression against a public register. A JWT is a printed form, with fields for "to", "from" and "valid until", that can be sealed either way.

The analogy is useful but undersells one thing, and it is the thing that matters most. A wax seal only protects what it physically covers. Press it on the corner of an envelope instead of over the fold and it proves nothing about the letter inside. Signatures behave the same way, and as our experiment showed, a JWT can carry a perfect seal over its own form while the letter it travels with stays wide open.

The useful question is never which seal looks more official. It is what the wax actually covers.

How HMAC signature webhooks work in practice

Here is the general recipe, which nearly every major provider follows with small variations. The sender and receiver share a secret. For each delivery, the sender builds a string from some combination of a message ID, a timestamp and the raw request body, computes HMAC-SHA256 over it with the secret, and puts the result in a header. The receiver rebuilds the same string from the request it received, computes the same HMAC, and compares the two values with a constant-time function. If they match and the timestamp is recent, the delivery is accepted.

The variations matter, because each one changes what the seal covers. We read the current documentation for each of these providers in November 2026.

ProviderSchemeHeaderWhat is signedFreshness check
GitHubHMAC-SHA256, hexX-Hub-Signature-256 (value starts with sha256=)Raw bodyNone documented
StripeHMAC-SHA256, hexStripe-Signature (t= and v1= entries)Timestamp, a dot, raw bodyLibraries default to 5 minutes
SlackHMAC-SHA256, hexX-Slack-Signature, X-Slack-Request-Timestampv0, timestamp and raw body joined by colons5 minutes
ZoomHMAC-SHA256, hexx-zm-signature, x-zm-request-timestampv0, timestamp and body joined by colonsTimestamp is signed; window is yours to set
ShopifyHMAC-SHA256, base64X-Shopify-Hmac-SHA256Raw body, keyed with the app's client secretNone documented; dedupe on X-Shopify-Webhook-Id
TwilioHMAC-SHA1X-Twilio-SignatureFull URL plus sorted form parameters, keyed with the account auth token; JSON bodies via a bodySHA256 URL parameterNo timestamp among the documented inputs
Standard Webhooks v1HMAC-SHA256, base64webhook-id, webhook-timestamp, webhook-signatureMessage ID, timestamp and body joined by dotsRequired, tolerance left to the receiver
Discord interactionsEd25519 (asymmetric)X-Signature-Ed25519, X-Signature-TimestampTimestamp followed by raw bodyTimestamp is signed

A few details in that table deserve a closer look. GitHub still sends a legacy X-Hub-Signature header computed with HMAC-SHA1 and says it "is only included for legacy purposes". Its documentation publishes a test vector that is handy for checking your own code: the secret "It's a Secret to Everybody" and the payload "Hello, World!" should produce a signature beginning 757107ea. We ran that vector in both Python and Node 24 and got the documented value in both.

Stripe's header carries more than signatures. Alongside the timestamp and v1 signatures, its documentation describes optional secret, destination and payload entries for debugging, and warns in a callout that they "aren't covered by the HMAC" and must never be used to authenticate a request. It also sends a fake v0 signature on sandbox events, which your code must ignore. When you roll a Stripe signing secret, you can keep the old one alive for up to seven days, and during that window Stripe sends one v1 signature per active secret. Each retry gets a fresh timestamp and a fresh signature, so a retried event will not trip your freshness check.

Shopify's documentation notes that after you rotate an app's client secret, it can take up to an hour before deliveries are signed with the new one, so a receiver should be ready to accept either secret during that hour. Twilio is the outlier: it still uses HMAC-SHA1, signs the URL and parameters rather than a timestamp, and tells developers plainly not to write their own validation and to use its SDK instead.

The Standard Webhooks specification, an open effort whose repository has passed 1,800 stars on GitHub, is the closest thing the industry has to a shared answer. It signs msg_id.timestamp.payload, requires a random secret of between 24 and 64 bytes, and lets the signature header carry several space-separated signatures so a provider can rotate keys with zero downtime. It also tells receivers to treat the webhook-id as an idempotency key, which connects signature checking directly to the idempotent webhook handlers any serious receiver needs anyway.

The pattern across the best of these is consistent: sign the ID, the time and the exact bytes, and nothing less.

Where JWT-based webhooks actually show up

Most comparison articles describe JWT webhooks in the abstract. They exist, and the real ones are instructive, because each solves the body problem differently, or does not try to.

Plaid puts a JWT in a Plaid-Verification header. Its documentation tells receivers to check that the header's alg field is exactly ES256 and reject anything else, read the kid (key ID), fetch the matching public key from Plaid's webhook_verification_key endpoint, verify the signature, reject tokens whose iat (issued-at) is more than five minutes old, and then compare a request_body_sha256 claim against a SHA-256 hash of the body. Plaid adds a warning that the hash is sensitive to whitespace, and that its bodies use two-space indentation. That last step is the seal over the fold.

FusionAuth, the identity platform, does the same thing with an X-FusionAuth-Signature-JWT header carrying a request_body_sha256 claim. It lets you sign with an EdDSA, EC or RSA key, publishing the public half at the standard /.well-known/jwks.json path, or with an HMAC key, which its documentation notes "requires manual key distribution".

Google Cloud Pub/Sub push subscriptions take a different route. Pub/Sub signs an OpenID Connect JWT and sends it in the Authorization header as a bearer token. Google's sample header shows RS256. Receivers are told to verify the signature against Google's public keys, check the issuer, check that the audience and email claims match the subscription's configuration, and confirm email_verified is true. Google also notes that these tokens "may be up to an hour old". Nothing in the documented claims refers to the message body. The token proves that Google's push service, acting as a particular service account, sent a request to you. It does not, by itself, prove what the request said.

Microsoft Graph change notifications with resource data are the most layered design we found. Each notification carries a validationTokens array of JWTs, one per app and tenant pair. Microsoft's documentation lists the checks: the token is not expired, it was issued by the Microsoft identity platform (whose signing keys, it notes, are "rotated daily"), its audience is your app's ID, and its azp or appid claim equals the Graph change-tracking service's fixed app ID. The resource data itself arrives encrypted under a one-time key, which is in turn encrypted with a public key you supplied when subscribing, and its integrity is checked with an HMAC-SHA256 dataSignature. In other words, Microsoft uses a JWT to say who sent the notification and an HMAC to seal the contents. It is the clearest real-world illustration that the two are layers, not rivals.

There is also a world where the JWT is the webhook. Security Event Tokens, defined in RFC 8417 in July 2018, are JWTs describing security events such as a revoked session. RFC 8935, from November 2020, standardizes pushing them over HTTP POST with the media type application/secevent+jwt. The OpenID Foundation approved its Shared Signals Framework 1.0 as a final specification in September 2025, and that framework profiles RFC 8935 as its push delivery method. Here the payload and the token are one object, so the signature covers everything by construction.

The turn: a token on the outside is not a seal on the fold

Line those designs up and the "HMAC vs JWT" frame falls apart. Plaid and FusionAuth use JWTs and seal the body. GitHub and Shopify use HMAC and seal the body but not the time. Stripe, Slack, Zoom and Standard Webhooks seal the body and the time. Pub/Sub uses a JWT that seals the sender's identity and audience while leaving the body to TLS. Microsoft uses both. The format tells you almost nothing about the protection. Three other questions tell you nearly everything.

What does the signature cover? The OWASP Webhook Security Cheat Sheet recommends a scheme that authenticates "the event ID, delivery timestamp, and raw request body together". Anything less leaves a gap. Without the body, a valid token can travel with a modified payload, which is exactly what our experiment showed. Without the timestamp, a captured delivery can be replayed indefinitely. Without the ID, you cannot reliably tell a replay from a retry.

Who holds the key? With HMAC, including HS256 JWTs, every party that can verify can also forge. If a provider sends webhooks to ten thousand customer endpoints with a per-endpoint secret, a leak at one customer exposes only that customer. But a single secret shared across several internal consumers means any one of them can mint valid messages for all the others. Asymmetric signatures split those powers: only the sender can sign, and anyone can verify.

How do keys rotate? HMAC rotation means two secrets valid at once for a window (Stripe allows up to seven days; Standard Webhooks sends both signatures side by side). Asymmetric rotation means publishing a new public key under a new kid and letting receivers fetch it, which is what JWKS endpoints exist for.

Now the honest caveat, which belongs in the middle rather than at the end. A bearer JWT that does not cover the body is not broken. Over TLS, an attacker on the network cannot alter the body in transit. The risk is narrower: anyone who obtains a valid token, from a log line, a misconfigured proxy or a debugging tool, can pair it with a body of their choosing until the token expires, which for Pub/Sub can be up to an hour. Whether that matters depends on what your handler does with the body. If it treats the body as a hint and fetches the real state from the provider's API, the exposure is small. If it trusts an amount field and ships goods, it is not.

HMAC vs JWT was never the decision. Coverage, key custody and rotation are the decision, and either format can get all three right or all three wrong.

HMAC vs RSA in JWT: HS256, RS256, ES256 and EdDSA

Many of the related searches, "jwt hmac vs rsa", "hmac256 jwt", "hmac sha256 vs jwt", are really asking about this layer: inside a JWT, should the signature be symmetric or asymmetric?

HS256 is HMAC-SHA256 under JWS. RFC 7518, the JSON Web Algorithms standard, says that "a key of the same size as the hash output (for instance, 256 bits for HS256) or larger MUST be used". The JWT Best Current Practices document, RFC 8725 from February 2020, goes further: human-memorable passwords "MUST NOT be directly used as the key" for HS256, because anyone who captures a single token can try to brute-force the key offline. HS256 is fast, simple and fine when one sender and one receiver both control their own security.

RS256 (RSA with SHA-256), ES256 (ECDSA on the P-256 curve) and EdDSA (usually Ed25519) are asymmetric. The sender signs with a private key, and receivers verify with a public key they can fetch from a JWKS endpoint, matched by the kid in the token header. Nobody who verifies can forge. That is a real security property for webhooks, and the Standard Webhooks specification says so directly: "If you do not control the security of both the producer and consumer, it is recommended you use an asymmetric signature instead." Its own asymmetric option, the v1a scheme, uses Ed25519 without any JWT at all, which is a reminder that asymmetric signing and JWT are separate choices too.

Among the asymmetric options, the differences are mostly practical. RSA signatures are large, and RSA keys take real time to generate, but verification is cheap. ES256 and EdDSA give much shorter signatures. We generated tokens carrying the same six claims (issuer, audience, issued-at, expiry, an ID and a body hash) to see what each costs on the wire.

What we generatedLength in characters
GitHub-style header value (sha256= plus hex HMAC)71
Standard Webhooks v1 signature value (v1, plus base64 HMAC)47
JWT, HS256359
JWT, ES256417
JWT, EdDSA (Ed25519)417
JWT, RS256 with a 2048-bit key673

None of those sizes will trouble an HTTP header limit, but the table makes one thing visible: most of a JWT's bulk is its claims, not its signature. If you do not need the claims, a plain signature header carries the same proof in a fraction of the space.

Pocket glossary: the terms in every webhook auth argument

  • HMAC: a keyed hash (RFC 2104). Same secret to create and to check.
  • JWS / JWT: JSON Web Signature is the signing format; a JSON Web Token is a signed set of claims built on it.
  • HS256: HMAC-SHA256 used as a JWT signature. Symmetric.
  • RS256, ES256, EdDSA: RSA, ECDSA P-256 and Ed25519 signatures. Asymmetric: private key signs, public key verifies.
  • JWK / JWKS and kid: a public key in JSON form, a published set of them, and the key ID that tells a receiver which one to use.
  • iat, exp, aud, iss: issued-at, expiry, audience and issuer claims inside a JWT.
  • Body hash claim: a claim such as request_body_sha256 that ties a JWT to the exact request body.
  • Constant-time compare: a comparison that takes the same time whether the first or last byte differs, so it leaks nothing about the expected value.
  • Replay window: how old a signed timestamp may be before you reject it. Five minutes is the common default.

What we measured: speed does not decide this

Claims that one method is meaningfully faster for webhook traffic circulate widely and rarely come with a method attached. So we measured. On a laptop with an AMD Ryzen 7 processor, using Python 3.12.10, PyJWT 2.15.1 and the cryptography library 50.0.2, we timed a full verification for each approach, averaged over thousands of runs, and repeated the whole run twice.

  • Raw HMAC-SHA256 over a small body plus a constant-time compare: about 2.4 to 2.6 microseconds.
  • JWT with HS256, full decode including issuer and audience checks: about 51 to 58 microseconds.
  • JWT with RS256: about 79 to 80 microseconds.
  • JWT with ES256: about 109 to 110 microseconds.
  • JWT with EdDSA: about 126 to 137 microseconds.
  • A bare Ed25519 verification, no JWT: about 117 to 127 microseconds.

Three caveats keep these numbers honest. They come from one machine and one language, and Python adds overhead that a Go or Rust receiver would not. Most of the HS256 figure is JSON parsing and claim checking rather than cryptography, which is why it is twenty times the raw HMAC. And RSA verification beating ECDSA is expected, not a fluke: RSA is slow to sign and cheap to verify.

The conclusion survives all three. The slowest option we tested still verifies in well under a fifth of a millisecond. A single network round trip, a database write or a queue publish inside your handler costs far more. The Standard Webhooks specification is right that HMAC is "much faster than any asymmetric scheme", and that matters for a provider signing millions of deliveries an hour. For a receiver, verification cost is a rounding error. Choose on coverage and key custody, not on microseconds.

The failures that actually break webhook authentication

Most real incidents come from the plumbing around the signature rather than the choice of algorithm. These are the ones we see most often, each checked against a primary source or reproduced on our machine.

Re-serializing the body. A framework parses JSON, the handler serializes it back to a string, and the signature check runs on the new string. We tried it: Python's json.dumps turned {"id":"evt_1","amount": 500} into a version with different spacing, and verification failed. The Standard Webhooks spec calls this "a very common failure mode", and Stripe's documentation warns that any manipulation of the raw body causes verification to fail. Always verify against the exact bytes you received.

Comparing with ==. The OWASP cheat sheet puts it bluntly: plain equality "leaks timing information and can turn the endpoint into a signing oracle". In Node, the safe function has a trap of its own: crypto.timingSafeEqual throws an ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH error when the two buffers differ in length, which we confirmed on Node 24.22.1. A forged header of the wrong length then produces an unhandled exception and a 500 response instead of a clean 401. Check lengths first.

No freshness check. A signature proves a message is authentic, not that it is new. GitHub and Shopify document no signed timestamp, so a captured delivery stays valid. OWASP's guidance for the other case is specific: reject deliveries outside a small tolerance, and keep each processed event ID "for at least twice the tolerance, 10 minutes for a 5-minute window". Stripe adds a warning worth repeating: a tolerance of 0 in its libraries disables the recency check entirely.

Trusting the token's own word about its algorithm. This is the classic JWT failure, and RFC 8725 describes both variants. An attacker sets alg to "none" and some libraries skip the signature. Or an attacker takes a system expecting RS256, switches the header to HS256, and signs with the server's public key as if it were an HMAC secret, so a naive library verifies it with that same public key. These were not theoretical. CVE-2015-9235 covered exactly that confusion in the Node jsonwebtoken package before version 4.2.2. CVE-2022-23540 described jsonwebtoken up to 8.5.1 falling back to the none algorithm when callers did not specify algorithms, fixed in version 9.0.0. As recently as December 2024, CVE-2024-54150 reported the same HMAC-for-RSA confusion in cjwt, a C library, fixed in version 2.3.0. The update to the JWT best practices now in the RFC Editor's queue adds a newer twist: libraries that blocklisted "none" but compared case-insensitively let attackers through with "noNE".

We checked how a current library behaves. PyJWT 2.15.1 refused to decode at all without an explicit algorithms list, rejected an alg of none when we allowed only HS256, and refused to use an RSA public key in PEM form as an HMAC secret, raising an error that the key "should not be used as an HMAC secret". Modern defaults are much safer than they were in 2015. The rule that protects you on any library is still the same one: pass an allowlist with exactly the algorithm you expect.

Reading the key from the request. The Standard Webhooks spec warns receivers not to "blindly trust signatures produced by untrusted public keys (e.g. by reading the public key from an additional header from the request payload)". The same applies to a JWT whose header points at a key URL you do not control. Keys come from a trusted list or a JWKS endpoint you configured, never from the message.

Failing loudly in the wrong place. Verification failures should return a 4xx quickly and log enough to debug (Stripe's debug entries exist for this). They should not throw into your retry machinery, where a provider's automatic retries turn one bad signature into hours of noise. Our guide to retries and dead letter queues covers where rejected deliveries should go, and the trade-offs in dead letter queue versus retry backoff apply here too.

Every one of these mistakes is invisible in a demo and obvious in an incident review.

The 2026 picture: standards are finally converging

For most of the last decade, webhook authentication was a set of private dialects. HMAC itself is nearly thirty years old, but each provider chose its own header names, its own string to sign and its own encoding: hex here, base64 there, colons for Slack and Zoom, dots for Stripe. Receivers wrote one verifier per provider and hoped they got each one right.

Three developments this year and last are pulling that together. The first is Standard Webhooks, now at version 1.0.0 of its specification, which offers one header set and one signing string for both HMAC (v1) and Ed25519 (v1a). Its introduction says it hopes to "do for webhooks what JWT did for API authentication", which is a neat irony for an article about choosing between them. On October 30, 2026, the project added an extension for webhook endpoint verification, a challenge that lets a sender confirm an endpoint has opted in and holds the right key before it sends real events, much like Zoom's existing URL validation handshake, which expects a hashed token back within three seconds.

The second is the update to the JWT rulebook. The IETF draft that will replace RFC 8725, draft-ietf-oauth-rfc8725bis, reached its tenth revision on August 21, 2026, and the IETF datatracker shows it in the RFC Editor's queue as of November 6. It adds threats discovered since 2020, including cross-JWT confusion (a token minted for one purpose accepted for another), the case-insensitive "noNE" bypass, and a recommendation for explicit typing through the typ header so different kinds of JWTs cannot be swapped. For webhook senders using JWTs, explicit typing is a cheap win: a webhook token that cannot be mistaken for a login token closes a whole class of mistakes.

The third is the Shared Signals Framework, final since September 2025, which made pushed JWTs the standard transport for security events between identity providers and apps. If your product receives session-revocation or account-risk events from an identity provider in the next few years, there is a good chance they will arrive as signed tokens rather than HMAC-signed JSON.

The broader trend is the same one our coverage of GitHub's pull_request_target change described in a different corner of the ecosystem: platforms are shifting from "trust whatever arrives" toward explicit, verifiable statements about who sent what. Webhook signatures are part of that shift, and the standards are finally catching up with the best provider practice.

OAuth2 vs JWT, and where each meets a webhook

Two of the most common related searches, "which is better jwt or oauth2" and "difference between oauth2 and jwt", rest on the same confusion as HMAC vs JWT. OAuth 2.0, defined in RFC 6749 in October 2012, is an authorization framework: a set of flows by which an application obtains permission, in the form of an access token, to act on a resource. JWT is a token format. An OAuth access token can be a JWT, and RFC 9068 from October 2021 defines exactly that profile, or it can be an opaque random string the server looks up. Asking which is better is like asking whether a passport office is better than a passport.

OAuth touches webhooks in two places. Some providers let the sender authenticate to your endpoint with credentials you configure. Zoom's documentation, for example, lists Basic, Token (OAuth) and custom header options alongside its HMAC signature. More often, OAuth governs the opposite direction: the call your receiver makes back to the provider's API after a webhook arrives. Stripe's recommended "thin" events work this way. The webhook carries little more than an ID, and the handler fetches the current object from the API with its own credentials. Our API coverage goes deeper on token handling for those calls.

Event-driven vs polling: when you can sidestep the problem

There is one way to avoid inbound authentication entirely: do not accept inbound requests. With polling, your system calls the provider's API on a schedule using its own credentials, and every byte you receive comes back over a connection you opened, to a host you verified through TLS. There is nothing to sign because there is nothing unsolicited to trust. The security event world even standardizes both modes, with RFC 8935 for push and RFC 8936 for poll-based delivery of the same tokens.

The cost is latency and wasted calls, which is why most integrations push. Our earlier piece on event-driven vs polling covers that trade-off in detail. A useful middle path is the thin webhook: treat the push as a doorbell and fetch the real state before acting. The Standard Webhooks spec points out that thin payloads also make data access auditable, because receivers must explicitly ask for what they need. A forged doorbell can, at worst, make you look something up. That design is also the right default for AI agents that act on webhooks, where a convincing fake payload could otherwise steer an agent into a real action.

HMAC vs JWT for webhooks: a decision framework

Here is the sequence we would follow, whether you are designing a sender or hardening a receiver.

  1. If you are a receiver, use the provider's scheme exactly and their official library where one exists. You do not get to choose. Twilio explicitly says not to write your own validation; Stripe recommends its libraries. Verify against raw bytes, compare in constant time, and add a replay window and an ID cache if the provider does not sign a timestamp.
  2. If you are a sender, decide who holds the key. If each customer endpoint gets its own random secret and you are comfortable that customers can protect it, HMAC-SHA256 is the simplest correct choice. If verifiers should never be able to forge, or you cannot vouch for how receivers store secrets, use asymmetric signatures.
  3. Decide what the signature covers before you pick a format. Message ID, timestamp and raw body, every time. If you choose a JWT, include a body hash claim such as request_body_sha256, as Plaid and FusionAuth do, or put the payload inside the token itself.
  4. Use a JWT only when you need what a JWT adds. That means audience and issuer claims for multi-tenant routing, standard key discovery through JWKS, or interoperability with identity tooling such as Shared Signals receivers. If you need none of those, a Standard Webhooks style header gives you the same security with less to get wrong.
  5. Pin the algorithm. One algorithm per key, an allowlist of one in every verify call, and explicit typing with a typ header if your JWTs could be confused with other tokens.
  6. Plan rotation on day one. For HMAC, support two valid secrets at once, the way Stripe allows a seven-day overlap and Standard Webhooks sends multiple signatures. For asymmetric keys, publish new keys under new kids before you start using them.
  7. Test the failure paths, not just the happy path. Discord's approach is worth copying: it deliberately sends invalid signatures to registered endpoints as a routine check and removes the URL of any endpoint that accepts them. Replaying recorded deliveries with one byte changed, as we describe in our piece on gates that replay real traffic, catches most of the mistakes above before production does.

Who should not use JWTs for webhooks: a small team sending to a handful of known receivers, with no need for claims, gains complexity and a larger attack surface in its libraries for no added protection. Who should not use shared HMAC secrets: a platform where many parties verify the same stream, or where a verifier being able to forge messages would be a serious problem. And nobody should use a bearer token that skips the body for anything that moves money or grants access without fetching the real state first.

Receiver code that holds up

These three snippets are short on purpose. We ran each of them against valid, tampered and stale inputs before publishing, and they accepted and rejected exactly what they should.

An HMAC verifier in Python for the Standard Webhooks format. The secret is the bytes you get after removing the whsec_ prefix and base64-decoding the rest.

import base64, hashlib, hmac, time

TOLERANCE = 300  # seconds

def verify_hmac(secret: bytes, msg_id: str, ts: str, raw_body: bytes, sig_header: str) -> bool:
    if abs(time.time() - int(ts)) > TOLERANCE:
        return False
    signed = f"{msg_id}.{ts}.".encode() + raw_body
    expected = base64.b64encode(hmac.new(secret, signed, hashlib.sha256).digest()).decode()
    for part in sig_header.split(" "):
        version, _, sig = part.partition(",")
        if version == "v1" and hmac.compare_digest(sig, expected):
            return True
    return False

A JWT verifier in Python that also seals the body, in the Plaid and FusionAuth style. The algorithm list has one entry, and the required claims are enforced by the library.

import hashlib, hmac, jwt

def verify_jwt_webhook(token: str, raw_body: bytes, public_key) -> dict:
    claims = jwt.decode(
        token, public_key,
        algorithms=["ES256"],
        audience="https://api.example.com/hooks",
        issuer="https://sender.example.com",
        options={"require": ["exp", "iat", "aud", "iss"]},
        leeway=30,
    )
    body_hash = hashlib.sha256(raw_body).hexdigest()
    if not hmac.compare_digest(claims.get("request_body_sha256", ""), body_hash):
        raise ValueError("body does not match the signed hash")
    return claims

And a GitHub verifier in Node that cannot crash on a malformed header. Pass it the raw body buffer, not a parsed object.

const crypto = require("crypto");

function validGitHubSignature(rawBody, header, secret) {
  const got = Buffer.from(header || "", "utf8");
  const want = Buffer.from(
    "sha256=" + crypto.createHmac("sha256", secret).update(rawBody).digest("hex"),
    "utf8"
  );
  return got.length === want.length && crypto.timingSafeEqual(got, want);
}

Once a delivery passes, acknowledge it quickly and process it from a queue. Microsoft Graph asks for a 202 before you even validate, and Stripe tells you to return a 2xx before any slow work. If processing spans several systems, the saga pattern for webhooks shows how to undo half-finished steps cleanly. For more of our reporting on delivery, signing and provider changes, our webhooks coverage collects it in one place.

Seal the fold, then choose the wax

There is a limit to what any of this can promise. A perfect signature tells you a message came from someone holding the key and has not changed since. It cannot tell you the sender's systems were not compromised, that the event is not a duplicate of one you already processed, or that the data inside is still current. Those jobs belong to idempotency, to fetching fresh state, and to the rest of a well-built receiver. Signature checking is the front door, not the whole house.

It is also worth imagining the counterfactual. If the industry had settled on JWTs for webhooks in 2015, we would be having the same argument from the other side: bearer tokens that forgot the body, libraries that trusted the alg header, secrets that were really passwords. The format would have changed and the mistakes would not, because the mistakes were never about format.

So the next time a design review stalls on "HMAC or JWT", the useful move is to set the question aside and ask three others instead. What does the seal cover? Who holds the ring? How does the ring get replaced? Answer those, and the format usually picks itself. Credit where it is due: the providers that got this right, from Stripe's timestamped signatures to Plaid's body hash and Microsoft's layered design, did it by asking those questions first.

FAQ

Is HMAC or JWT better for webhooks?

For most webhooks, HMAC-SHA256 over the message ID, timestamp and raw body is simpler and just as secure. A JWT is better when receivers should verify with a public key and must not be able to forge messages, or when you need signed claims such as audience. Either way, the signature must cover the body and a timestamp.

Is a JWT signed with HS256 the same as HMAC?

Yes, at the cryptographic level. HS256 means the JWT's signature is computed with HMAC-SHA256 over the token's header and claims. The difference is packaging: a JWT adds a standard header and claims like expiry. It does not cover the HTTP body unless the claims include the payload or a hash of it, such as request_body_sha256.

HMAC vs RSA for JWT: which should I use?

Use HS256 when one sender and one receiver share a strong random key of at least 256 bits and both protect it. Use an asymmetric algorithm such as ES256, EdDSA or RS256 when several parties verify, or when a verifier must not be able to sign. In our tests, ES256 and EdDSA tokens were roughly 38 percent shorter than RS256 tokens carrying the same claims.

What is the difference between OAuth2 and JWT?

OAuth 2.0 is an authorization framework for obtaining access tokens; JWT is a token format. They are not alternatives. An OAuth access token can be a JWT, as RFC 9068 defines, or an opaque string. With webhooks, OAuth usually governs the API calls your receiver makes back to the provider, while HMAC or JWT signatures authenticate the incoming delivery.

How do I stop webhook replay attacks?

Sign a timestamp together with the body, reject deliveries outside a tolerance of about five minutes, and record each processed message ID for at least twice that window, as the OWASP Webhook Security Cheat Sheet advises. If the provider signs no timestamp, as with GitHub, rely on delivery IDs and idempotent handlers instead.