← Back to section · Tutorials & Labs

Signing API Requests: HMAC in Practice with Full Replay Protection

Open APIs commonly use HMAC signatures to prove a request really came from the key holder and was not tampered with. This tutorial implements signing and verification for an API request end to end with the standard library's hmac module: a canonical signing string, timestamps and nonces against replay, constant-time comparison, and a dissection of the signing mistakes beginners make most.

Published 22 November 2026 · 7 min read · PQ Frontier

Signing API Requests: HMAC in Practice with Full Replay Protection
AI-generated site artwork
Video explainer · Python cryptography: experiments and prototypes

What this tutorial aims to do

When a system opens an interface to partners, the most common authentication mechanism is not a username and password but an HMAC signature: the two sides share a key in advance, the caller computes a signature for each request and attaches it in a header, and the server recomputes it with the same key and compares. A matching signature proves three things at once: the request came from the key holder, the content was not altered in transit, and the key itself never travelled over the network. This tutorial implements the whole chain in Python’s standard library — signing, verification and replay protection, nothing omitted — and explains why each link must be the way it is. The introductory tutorial already showed the basic HMAC usage; this one advances it to the complete shape used by real interfaces.

The signing string: canonicalize first, then sign

The most common failure point of HMAC signing is not the algorithm but the question “what exactly is being signed”. If the two sides disagree about any of the request method, path, query parameters or body, the signatures will never match; worse, any ambiguity leaves room for an attacker to alter a request without invalidating its signature. The engineering convention is therefore to define a canonical signing string first: join every element worth protecting in a fixed order with fixed separators, hashing the body with SHA-256 before including it (so large bodies need not enter the signature computation whole, while the hash still represents them completely). This tutorial uses five parts: method, path, timestamp, nonce and body hash. The timestamp and nonce are both replay-protection material and signed content, so an attacker who tampers with them invalidates the signature.

import hashlib, hmac, secrets, time

SECRET = b"shared-secret-key"  # shared in advance; never appears in a request

def build_signing_string(method: str, path: str, body: bytes,
                         timestamp: int, nonce: str) -> str:
    body_hash = hashlib.sha256(body).hexdigest()
    return "\n".join([method.upper(), path, str(timestamp), nonce, body_hash])

def sign_request(method: str, path: str, body: bytes) -> dict:
    timestamp = int(time.time())
    nonce = secrets.token_hex(16)
    text = build_signing_string(method, path, body, timestamp, nonce)
    signature = hmac.new(SECRET, text.encode("utf-8"), hashlib.sha256).hexdigest()
    return {"X-Timestamp": str(timestamp), "X-Nonce": nonce,
            "X-Signature": signature}

Verification and replay protection

On receiving a request the server does four things, in an order that matters. Step one, check the timestamp: reject any request whose timestamp differs from server time by more than the allowed window (five minutes is common), which compresses every signature’s useful lifetime to something short. Step two, check the nonce: keep a set of nonces seen within the window and reject repeats — timestamp plus nonce deduplication is the complete replay defence: old requests cannot enter after the window closes, and within the window they cannot enter twice because their nonce is already registered. Step three, recompute the signature under the same canonicalization rules. Step four, compare with hmac.compare_digest in constant time, avoiding the byte-by-byte short-circuit of ordinary string comparison, which would hand attackers a timing side channel for guessing the correct signature one position at a time.

SEEN_NONCES = set()  # in-memory set for the demo; production uses expiring storage

def verify_request(method: str, path: str, body: bytes,
                   headers: dict, now: int | None = None) -> bool:
    now = int(time.time()) if now is None else now
    try:
        timestamp = int(headers["X-Timestamp"])
        nonce = headers["X-Nonce"]
        signature = headers["X-Signature"]
    except (KeyError, ValueError):
        return False
    if abs(now - timestamp) > 300:          # timestamp window: five minutes
        return False
    if nonce in SEEN_NONCES:                # each nonce may be used only once
        return False
    text = build_signing_string(method, path, body, timestamp, nonce)
    expected = hmac.new(SECRET, text.encode("utf-8"), hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, signature):
        return False
    SEEN_NONCES.add(nonce)
    return True

headers = sign_request("POST", "/v1/transfer", b'{"amount": 10}')
print(verify_request("POST", "/v1/transfer", b'{"amount": 10}', headers))  # True
print(verify_request("POST", "/v1/transfer", b'{"amount": 10}', headers))  # False: replay
print(verify_request("POST", "/v1/transfer", b'{"amount": 99}', headers))  # False: tampered

Managing the keys: identifiers, rotation and query parameters

Once the signing chain runs, the remaining engineering problems gather around key management. First, key identifiers: real systems usually hold several keys at once — one per partner, or an old and a new key for the same partner — so the request headers should carry a key-ID field stating which key produced this signature, letting the server fetch the right key instead of trying each in turn. Second, rotation: keys should be replaced regularly, and rotation should be designed as a dual-key overlap period — for a while after the new key is published, both old and new verify successfully, callers migrate at leisure, and only after the transition window does the old key retire; without that design, every rotation is a full outage. Third, canonicalizing query parameters: this tutorial’s signing string omits them, but real interfaces often carry a query string after the path, and proxies in transit may reorder parameters or rewrite their encoding; unless both sides agree on sorting and encoding rules in advance, signatures will fail for no visible reason. The robust approach is to sort query parameters by name, rebuild them under one percent-encoding rule, and only then include them in the signing string, so that no intermediary’s reordering can change the result. None of these three involves new cryptography, yet together they decide whether a signing scheme survives its first month in a real system.

Sign-then-encrypt or encrypt-then-sign: why the order hides traps

One classic protocol-design question deserves its own paragraph: when an interface requires both signing and encryption, their order must not be chosen casually. If you sign the plaintext and then encrypt (sign-then-encrypt), the receiver can verify after decrypting, but the signature sits wrapped inside the ciphertext, so no third party can confirm origin without decrypting; worse, in some forwarding scenarios an intermediary can strip the outer encryption, re-wrap the signed plaintext in its own encryption layer, and make the receiver believe the ciphertext also came from the original sender — the very trap several encrypted-mail protocols fell into. The safer general principle: the signature should cover the exact byte form that appears on the wire, or the protocol should bind the sender’s identity explicitly into both the signed content and the encryption context, leaving no room for “re-shelling” attacks. In this tutorial’s API-signing scenario, requests ride over HTTPS while the signature targets the canonicalized plaintext string; that combination holds because TLS already supplies channel-level origin binding. Step away from TLS and design your own, and the ordering question becomes a formal protocol-review item rather than an implementation detail decided on the fly.

The four signing mistakes beginners make most

Mistake one: faking a signature with a plain hash, such as appending the key to the request and taking one SHA-256 over it — ordinary hashes have structural weaknesses such as length extension, home-made constructions of this kind are forgeable in multiple scenarios, and HMAC’s nested two-pass structure exists precisely to repair them; always use the hmac module. Mistake two: signing only the body and not the method and path, which lets an attacker deliver a request signed for interface A verbatim to interface B with the signature still valid — the signed content must cover every element with security meaning. Mistake three: no timestamp and no nonce, so signatures never expire and a captured request can be replayed indefinitely, hollowing out the whole mechanism. Mistake four: placing the key inside the request parameters “to make verification convenient”, which amounts to mailing the key together with the lock — anyone who intercepts one request can impersonate the caller forever. Finally, one boundary to state plainly: HMAC signatures provide authenticity and integrity, not confidentiality; request content still needs HTTPS on the wire. Signing answers “who sent it and was it changed”, encryption answers “can anyone else read it”, and neither substitutes for the other.

Tags: PythonHMACAPI SigningReplay Protection