How-to › Authenticate and authorize calls

How to verify HMAC-signed requests and reject replays#

Recompute an HMAC over the raw request bytes, compare it in constant time, enforce a timestamp window, and claim each nonce in Redis to refuse a copied request.

Audience
API producer
Level
intermediate
Topic
Sign requests and use mTLS
Languages
TypeScript, Python and Go
Verified

Your API checks an HMAC-SHA256 signature on every request, so a forged POST /orders fails. A signed request copied from a proxy log still passes: sent again thirty seconds later, its bytes and its signature are unchanged, and the server creates a second order. A JSON body parser in front of the check causes the opposite failure, refusing requests that were signed correctly.

What you get

You will end up with a verifier in Node, Python, and Go that checks the signature over the raw bytes in constant time. It refuses stale timestamps and any nonce already in a shared Redis. This is for you if your own API accepts signed requests.

Short answer

Read the request body as bytes, recompute HMAC-SHA256 over the timestamp, a nonce, the method, the path, and those bytes, and compare in constant time with timingSafeEqual, hmac.compare_digest, or hmac.Equal. Refuse a timestamp more than five minutes off. Then claim the nonce in Redis with SET NX EX, kept until the timestamp leaves the window, and refuse a request whose nonce is already there.

You will need

Node 22 or later, Python 3.12 or later, Go 1.24 or later, a Redis server that every API instance can reach, and a secret shared with each client. The sample uses only the standard library in each language, plus Express 5.3.0 for the body parser comparison. The client sends three headers: x-signature-timestamp in Unix seconds, x-signature-nonce of 16 to 128 URL-safe characters, and x-signature holding the hex digest.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
Idempotency-Key as nonceWrites already carry the header and the API already stores keysReads keep the whole replay gap, and the key must sit inside the signed bytesReads return data worth protecting, or some writes arrive without a key
Redis nonce cacheSeveral instances, and every request, reads included, must be accepted onceA network round trip per request, and a store whose outage must fail requests closedOne process serves all traffic, or every endpoint is safe to repeat
Timestamp window onlyRepeats are harmless and you want no shared stateAny captured request works again, unchanged, until its timestamp leaves the windowA repeated write moves money, stock, or permissions

AWS lists a window under replay protection for Signature Version 4: in most cases a request must reach AWS within five minutes of its timestamp. A window costs no storage, but a captured request stays usable until its timestamp leaves the window. A Redis cache closes the gap for every method and adds a store to the request path. Reusing the Idempotency-Key adds no store when you have one, but reads stay open.

Check the signature over the bytes that arrived

The verifier takes the raw body as a Buffer, and the time as a parameter so tests can move it. It checks the format first, the window second, and the signature last, and touches no store.

// Checks the format, the window and the signature, in that order, and returns
// the nonce for the caller to claim. Nothing here touches a store.
export function verifyRequest({
  secret, method, target, headers, rawBody, now,
  windowSeconds = WINDOW_SECONDS, nonceHeader = 'x-signature-nonce', nonceOptional = false,
}) {
  const ts = headers['x-signature-timestamp']
  const presented = headers['x-signature']
  const nonce = headers[nonceHeader]
  if (typeof ts !== 'string' || !TIMESTAMP.test(ts)) return fail('malformed timestamp')
  if (typeof presented !== 'string') return fail('missing signature')
  if (nonce === undefined && !nonceOptional) return fail('missing nonce')
  const pattern = nonceHeader === 'idempotency-key' ? SF_STRING : NONCE
  if (nonce !== undefined && (typeof nonce !== 'string' || !pattern.test(nonce))) return fail('malformed nonce')

  const timestamp = Number(ts)
  if (Math.abs(now - timestamp) > windowSeconds) return fail('outside the window')

  const expected = signature(secret, { timestamp: ts, nonce: nonce ?? '', method, target, rawBody })
  if (!signaturesMatch(expected, presented)) return fail('signature mismatch')
  return { ok: true, timestamp, nonce }
}

signaturesMatch checks the two lengths and then calls crypto.timingSafeEqual, which throws when the byte lengths differ. The method and the path are in the signed message, so a captured POST /orders cannot be pointed at /refunds.

The server collects the stream into a buffer and verifies before it parses anything.

  async function handle(req, res) {
    const rawBody = await readRaw(req)
    const clock = now()
    const v = verifyRequest({
      secret, method: req.method, target: req.url, headers: req.headers, rawBody, now: clock,
      ...(mode === 'idempotency' ? { nonceHeader: 'idempotency-key', nonceOptional: true } : {}),
    })
    if (!v.ok) return send(res, v.status, { error: v.reason })

    if (mode === 'nonce') {
      const claim = await claimNonce(store, v.nonce, nonceTtl(v.timestamp, clock))
      if (!claim.ok) return send(res, claim.status, { error: claim.reason })
    }

    // Parsing waits until the bytes are known to be the ones that were signed.
    const body = rawBody.length ? JSON.parse(rawBody.toString('utf8')) : null

Keep each nonce until its timestamp expires

A window of five minutes either side means a request signed by a client whose clock runs ahead stays acceptable for up to ten minutes. A nonce kept for the window alone expires while its request can still be sent again, so the TTL runs from the timestamp, not from the arrival.

// A timestamp up to the window ahead of this clock is accepted, and stays
// acceptable until it is the window behind. The nonce must live that long.
export function nonceTtl(timestamp, now, windowSeconds = WINDOW_SECONDS) {
  return timestamp + windowSeconds - now + 1
}

// SET key 1 NX EX ttl answers OK for a nonce it has not seen and nil for one it
// has. A store that cannot answer fails the request rather than waving it in.
export async function claimNonce(store, nonce, ttl) {
  let reply
  try {
    reply = await store.command('SET', `nonce:${nonce}`, '1', 'NX', 'EX', String(ttl))
  } catch {
    return fail('nonce store unavailable', 503)
  }
  return reply === 'OK' ? { ok: true } : fail('replay')
}

NX sets the key only if it does not exist, and the reply is nil when it did, so one command both checks and records. Two instances that race on one nonce cannot both get OK. The claim runs after the signature check, so unsigned traffic cannot fill the store.

The demo sends six requests to each of three servers that share one Redis stand-in and one controlled clock, and prints the answers to five of them. The first GET goes unprinted, so the row for the second shows what a repeated read gets.

node demo.mjs
scenario                  window only             nonce in Redis          Idempotency-Key
signed POST               201                     201                     201
same POST, +30 s          201                     401 replay              201 replayed
signed GET again, +30 s   200                     401 replay              200
POST, body edited         401 signature mismatch  401 signature mismatch  401 signature mismatch
POST signed 400 s ago     401 outside the window  401 outside the window  401 outside the window
orders created            2                       1                       1

The window alone created two orders from one signed request. The Idempotency-Key server answered the repeated POST with the stored order, as the draft asks of a duplicate, and let the repeated GET through.

Run the same check in two more languages

The Python verifier uses hmac.compare_digest, which returns False for unequal lengths rather than raising.

    timestamp = int(ts)
    if abs(now - timestamp) > window:
        return 401, "outside the window"
    expected = signature(secret, ts, nonce, method, target, raw_body)
    # compare_digest returns False for unequal lengths rather than raising.
    if not hmac.compare_digest(expected.encode(), presented.encode()):
        return 401, "signature mismatch"
    return 200, (timestamp, nonce)

Go’s hmac.Equal does the same job.1

	expected := signature(secret, ts, nonce, method, target, rawBody)
	// hmac.Equal returns false for unequal lengths, at once, and otherwise
	// takes the same time whatever the contents.
	if !hmac.Equal([]byte(expected), []byte(presented)) {
		return result{status: 401, reason: "signature mismatch"}
	}
	return result{status: 200, timestamp: timestamp, nonce: nonce}

The cross-check signs requests in Node and hands each one to the three verifiers in turn, all claiming nonces in the same store.

node crosscheck.mjs
case                                    python                      go                          node
one request, sent to each in turn       200 accepted                401 replay                  401 replay
body edited after signing               401 signature mismatch      401 signature mismatch      401 signature mismatch
signature cut to 63 characters          401 signature mismatch      401 signature mismatch      401 signature mismatch
signed 400 s before the server clock    401 outside the window      401 outside the window      401 outside the window
nonce store unreachable                 503 nonce store unavailable 503 nonce store unavailable 503 nonce store unavailable

The first row is the reason the cache is shared: a replay sent to another instance, in another language, still finds the nonce.

Check it worked

The suite asserts each row of the two tables and the expiry rule. This test moves the clock past a nonce kept for the window alone and watches the replay succeed:

test('the window as the TTL lets a replay of a clock-ahead request through; nonceTtl does not', async (t) => {
  const clock = { now: T0 }
  const store = await redisAt(t, clock)
  const ahead = T0 + 290 // the client clock runs 290 s fast, inside the window
  const naive = check(req({ timestamp: ahead, nonce: 'nonce-naive-000000001' }), clock.now)
  const fixed = check(req({ timestamp: ahead, nonce: 'nonce-fixed-000000001' }), clock.now)
  assert.equal((await claimNonce(store, naive.nonce, WINDOW_SECONDS)).ok, true)
  assert.equal((await claimNonce(store, fixed.nonce, nonceTtl(fixed.timestamp, clock.now))).ok, true)
  clock.now = T0 + 400 // the naive key has expired, and the timestamp is 110 s old
  assert.equal(check(req({ timestamp: ahead, nonce: 'nonce-naive-000000001' }), clock.now).ok, true)
  assert.equal((await claimNonce(store, naive.nonce, WINDOW_SECONDS)).ok, true, 'replay accepted')
  assert.equal((await claimNonce(store, fixed.nonce, nonceTtl(fixed.timestamp, clock.now))).reason, 'replay')
})

The Redis stand-in is held to the SET reference by redis-semantics.test.mjs, which record.sh also ran against redis-server 7.0.15. Run both files:

node --test verify.test.mjs redis-semantics.test.mjs
1..23
# tests 23
# suites 0
# pass 23
# fail 0
# cancelled 0
# skipped 0
# todo 0

When it goes wrong

Every correctly signed request fails behind Express. express.json() parsed the body, and the handler recomputed the HMAC over JSON.stringify(req.body), which drops the spaces the client sent. The verify option of express.json hands you the raw Buffer before parsing:

node pitfall.mjs
bytes on the wire        "{\"sku\":\"A-100\",  \"qty\":1}"
JSON.stringify(req.body) "{\"sku\":\"A-100\",\"qty\":1}"
express.json(), body re-serialized    401 {"error":"signature mismatch"}
express.json({ verify }), raw bytes   201 {"verified":true}

Every request fails with outside the window from one client. Its clock has drifted. Fix the clock rather than widening the window, because the window is the replay gap.

Every request fails with 503 while Redis restarts. claimNonce fails closed on purpose, so the API is down for as long as the store is. Failing open would accept every replay sent during the outage.

A replayed write goes through with the Idempotency-Key design. The key was sent outside the signed message, so a copied request with a fresh key passes as a first attempt. Sign the header value, quotes included, as sign.mjs does.2

When not to do this

Do not hand-roll this for webhooks you receive from a provider. The provider defines the scheme, and its own verification library or a published specification covers the edge cases.

Do not keep nonces in process memory once a second instance serves traffic. A replay routed to the other instance finds nothing there. The first row of the cross-check is that replay, refused only because the store is shared.

Do not return the reasons to callers. The demo prints them so you can see which check fired. A probe that learns whether it failed the window or the signature knows which half to work on, so log the reason and answer a bare 401.

Do not build HMAC request signing at all when you control both ends and can end TLS yourself. Mutual TLS authenticates the client per connection, with no shared secret to rotate on both sides and no nonce store, at the cost of running a certificate authority.

Last verified

Verified 2026-11-30 against Node 22.23.5, Python 3.13.18 and 3.12.3, Go 1.24.7 and 1.25.14, Express 5.3.0 with body-parser 2.4.0, and redis-server 7.0.15. Every output block is what the command preceding it printed. The commands use the Redis stand-in in redis-standin.mjs, and record.sh ran the SET semantics tests once against the real server, all but the millisecond-boundary test, which needs a clock that can be stopped.

Footnotes

  1. The three libraries disagree about unequal lengths. Node’s timingSafeEqual throws. Python’s compare_digest returns False, and its documentation concedes that a timing attack could in theory reveal the types and lengths, but not the values. Go’s hmac.Equal hands the work to subtle.ConstantTimeCompare, which returns at once when the lengths differ. A comment inside hmac.Equal says it need not be constant time then, as a different length suggests a completely different hash function was used. ↩︎ Back to text

  2. The draft is at revision 09, dated November 21, 2026, and due to expire on May 25, 2027. It makes the header’s value a Structured Field String, which RFC 9651 writes between double quotes and limits to printable ASCII. The quotation marks are part of the field value, so they are part of what gets signed. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.