Back to cheatsheets
Developer
API Authentication Patterns
HMAC-signed API requests with replay protection using timestamps and nonces.
What you'll learn
- Signed request
- Server-side verification
How to use these snippets
- Click the Copy button next to any snippet to copy it to your clipboard.
- Paste the code into your project, IDE, or terminal.
- Replace placeholder values (like
example.comoryour-secret) with your actual data. - Review the code comments for important security notes and caveats.
Code Snippets
Copy-paste code snippets
2 ready-to-use snippets for api authentication patterns. Click copy and paste into your project.
Signed request
async function signedRequest(url, key, body) {
const ts = Date.now();
const nonce = crypto.randomUUID();
const msg = `${ts}.${nonce}.${body}`;
const enc = new TextEncoder();
const ck = await crypto.subtle.importKey(
'raw', enc.encode(key),
{ name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
const sig = await crypto.subtle.sign(
'HMAC', ck, enc.encode(msg));
const sigB64 = btoa(String.fromCharCode(
...new Uint8Array(sig)));
return fetch(url, {
method: 'POST',
headers: {
'X-Timestamp': ts,
'X-Nonce': nonce,
'X-Signature': sigB64,
'Content-Type': 'application/json'
},
body
});
}
Server-side verification
async function verifyRequest(req, key) {
const ts = parseInt(req.headers['x-timestamp']);
const nonce = req.headers['x-nonce'];
const sig = req.headers['x-signature'];
// Check timestamp window (5 minutes)
if (Math.abs(Date.now() - ts) > 300000)
return false; // Expired
// Check nonce hasn't been used (requires cache)
if (await cache.has(nonce))
return false; // Replay attack
// Verify signature
const msg = `${ts}.${nonce}.${req.body}`;
const expected = await hmacSign(key, msg);
if (!await constantTimeEqual(sig, expected))
return false;
await cache.set(nonce, true, 300);
return true;
}
100% Free · No signup · No cost
Generate something unguessable right now
148 bits of entropy, a crack-time estimate you can trust, and a clipboard that clears itself after 30 seconds.
Part of the Toolly ecosystem · secure.toolly.site