ShieldX Toolly
Open a tool Donate
Home Home
Blog Blog
FAQ FAQ
Open a tool Donate
Back to cheatsheets
Developer

API Authentication Patterns

HMAC-signed API requests with replay protection using timestamps and nonces.

2 snippets Intermediate
HMACAPIreplay protectionnoncesigning

What you'll learn

  • Signed request
  • Server-side verification

How to use these snippets

  1. Click the Copy button next to any snippet to copy it to your clipboard.
  2. Paste the code into your project, IDE, or terminal.
  3. Replace placeholder values (like example.com or your-secret) with your actual data.
  4. 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.

Open the toolkit

Part of the Toolly ecosystem · secure.toolly.site