Sign API Requests with HMAC
Implement HMAC-based API request signing to authenticate clients and protect against tampering. Learn canonical request construction and signature header best practices.
Detailed Explanation
HMAC-Based API Request Signing
API request signing uses HMAC to authenticate the client making a request and ensure the request has not been tampered with in transit. Unlike API keys sent as static tokens, signed requests prove that the sender possesses the secret key without transmitting the key itself.
Why Sign API Requests?
Static API keys have several weaknesses:
- They can be intercepted if transmitted over a compromised connection
- They can be replayed — anyone who captures the key can use it indefinitely
- They provide no integrity protection — a man-in-the-middle can modify request parameters
HMAC signing addresses all three concerns. The signature is computed over the specific request parameters, so modifying any parameter invalidates the signature. Timestamps prevent replay attacks. And the secret key never appears in the request.
Canonical Request Construction
The most important step in request signing is constructing a canonical request — a deterministic string representation of the request that both client and server will compute identically:
canonical_request = HTTP_METHOD + "\n"
+ URI_PATH + "\n"
+ SORTED_QUERY_STRING + "\n"
+ SORTED_SIGNED_HEADERS + "\n"
+ HASHED_PAYLOAD
Key rules for canonicalization:
- Sort query parameters alphabetically by key name
- Lowercase all header names and trim whitespace
- Normalize the URI path (resolve
.and.., ensure leading/) - Hash the payload with SHA-256 (even if empty)
Constructing the Signature
string_to_sign = ALGORITHM + "\n"
+ TIMESTAMP + "\n"
+ SCOPE + "\n"
+ SHA256(canonical_request)
signature = HMAC_SHA256(signing_key, string_to_sign)
The Authorization Header
The final header includes the algorithm, credential scope, signed headers list, and the computed signature:
Authorization: HMAC-SHA256 Credential=KEY_ID/SCOPE,
SignedHeaders=content-type;host;x-date,
Signature=a3f2b8c1...
This pattern is used by AWS Signature V4, and many other services have adopted similar schemes.
Use Case
HMAC request signing is essential for building secure public APIs, implementing server-to-server authentication in microservices architectures, and meeting enterprise security requirements for non-repudiation and tamper detection.