---
title: "n8n Webhook Security: Verify Requests With HMAC"
description: "n8n webhook security with HMAC signature checks, replay protection, secret rotation and rate limits. A step-by-step setup you can test today."
canonical: "https://buildwithjit.com/articles/n8n-webhook-security-hmac-verification"
date: "Nov 29, 2026"
updated: "2026-12-03T11:22:40.792967"
category: "n8n Automation"
tags: [n8n, Webhook Security, HMAC, Automation]
---

# n8n Webhook Security: Verify Requests With HMAC

n8n webhook security is easy to skip because a webhook URL feels private. It is not: anyone who learns or guesses the URL can trigger your workflow, and many workflows send emails, write to databases or call paid AI models. This guide shows a pattern that verifies an HMAC signature before any other node runs, rejects old and replayed requests, lets you rotate secrets without downtime, and gives you a test plan to prove it works.

It is written for self-hosted n8n, but the ideas apply to any system that receives webhooks. You will get the threat model, the signing design, a copy-ready Code node, a sender script for testing, replay protection with Redis, proxy limits with Nginx, monitoring tips and a go-live checklist.

## Key takeaways: n8n webhook HMAC verification

- A secret URL is not authentication. URLs leak.
- Have the sender sign `timestamp + "." + raw body` with HMAC-SHA256 and send both in headers.
- Verify the signature in the first node after the Webhook node, using a constant-time comparison.
- Reject timestamps older than five minutes, and reject a signature you have already seen.
- Support two secrets during rotation so you never need downtime.
- Return a generic `401` or `409`. Keep the real reason in your own logs.
- Add rate and body-size limits at the proxy, and test six good and bad cases before going live.

## Why an open n8n webhook is risky

A production webhook URL works like a door with no lock unless you add authentication. URLs leak through server logs, browser history, screenshots, exported workflows, support tickets and shared chats. Hiding the path or adding a long random token to it only makes guessing harder. It does not prove who is calling.

The damage depends on what the workflow does after the trigger:

- **Spam executions** that fill your execution history and slow the instance.
- **Real cost**, when the workflow calls an LLM or another paid API on every request.
- **Bad data**, when fake payloads are written to your CRM, sheet or database.
- **Unwanted actions**, such as emails, WhatsApp messages, refunds or ticket updates.
- **Information leaks**, when the workflow responds with data about your systems.

n8n gives each Webhook node two URLs. The **test URL** only listens while you press "Listen for test event" in the editor. The **production URL** listens whenever the workflow is active. Security checks must work on the production URL, so always run your final tests against it.

### Threats and the control for each

| Threat | What it looks like | Control |
|---|---|---|
| Guessed or leaked URL | Random POST requests start workflows | Signature check before any other node |
| Captured request resent | The same valid request arrives again | Timestamp window plus duplicate detection |
| Body changed in transit | Amount, email or ID altered | HMAC covers the raw body |
| Leaked secret | Attacker can create valid signatures | Per-sender secrets, rotation, alerts on odd traffic |
| Flooding | Hundreds of requests per second | Rate limit and body-size limit at the proxy |
| Timing probing | Attacker measures how long comparison takes | Constant-time comparison |

## What HMAC does and does not do

HMAC (hash-based message authentication code) is defined in RFC 2104. The sender and the receiver share a secret. The sender hashes the message together with the secret, and the receiver repeats the calculation and compares the result.

**It gives you:**

- **Authenticity:** only someone who knows the secret can create a valid signature.
- **Integrity:** if one byte of the body changes, the signature no longer matches.

**It does not give you:**

- **Encryption.** The body is still readable on the wire, so you still need HTTPS.
- **Replay protection by itself.** A valid request is still valid if it is sent again, which is why this guide adds a timestamp and duplicate detection.
- **Authorization.** It proves who sent the request, not what that sender should be allowed to do.
- **Protection after a leak.** Anyone with the secret can sign requests until you rotate it.

## Design the signature before you build

Most mistakes come from a vague signing design. Decide these points first and write them down for the sender team, even if the sender is also you.

| Decision | Recommended choice | Why |
|---|---|---|
| Algorithm | HMAC-SHA256 | Widely supported and strong enough for this use |
| What to sign | `timestamp + "." + raw body` | The timestamp is covered, so it cannot be changed |
| Body format | Raw bytes exactly as sent | Parsed and re-serialised JSON can differ in spacing and key order |
| Signature header | `X-Signature`, lowercase hex, 64 characters | Easy to validate before any heavy work |
| Timestamp header | `X-Timestamp`, Unix seconds | Simple to compare with the server clock |
| Allowed age | 300 seconds | Tolerates small clock drift and slow networks |
| Secret | At least 32 random bytes, one per sender | A leak affects only one sender |

Keep the server clock accurate with NTP. If your server clock drifts, valid requests start failing the timestamp check and you will be tempted to widen the window, which weakens replay protection.

## n8n webhook security setup, step by step

The final workflow has this shape:

1. Webhook node
2. Code node that verifies the signature and timestamp
3. IF node: is the request valid?
4. Redis node that records the signature (duplicate detection)
5. IF node: is this the first time we saw it?
6. Your real workflow
7. Respond to Webhook node (`200`), with separate Respond nodes for `401` and `409`

### Step 1: Configure the Webhook node

- **HTTP Method:** `POST`
- **Path:** a descriptive path, not a guessable one such as `/webhook/test`
- **Authentication:** leave as None. The HMAC check is your authentication. If you also use Header Auth or Basic Auth, treat it as an extra layer, not a replacement.
- **Respond:** "Using 'Respond to Webhook' Node", so you decide the status code
- **Options → Raw Body:** enable it. This makes the exact bytes available as binary data, which is what the signature covers.
- **Options → IP(s) Whitelist:** add the sender's fixed IP addresses if it has them

n8n limits the size of incoming payloads (the `N8N_PAYLOAD_SIZE_MAX` setting). Check the default for your version and lower the limit at the proxy if your senders only ever send small bodies.

### Step 2: Store the secret outside the workflow

Keep secrets in environment variables on the server, not typed into a node. A workflow export, a screenshot or a shared workflow would expose a hard-coded value.

Use two variables so rotation never needs downtime:

- `WEBHOOK_SECRET_CURRENT`
- `WEBHOOK_SECRET_PREVIOUS` (empty except during rotation)

Some n8n setups block reading environment variables inside nodes (the `N8N_BLOCK_ENV_ACCESS_IN_NODE` setting). If that applies to you, ask whoever manages the instance to allow it, or use another secret store that your n8n plan supports.

### Step 3: Verify the signature in a Code node

Place this node directly after the Webhook node, in "Run Once for All Items" mode. Adjust the header names and the binary property name (`data`) to match your sender and what you see in the Webhook node's output.

```javascript
const crypto = require('crypto');

const item = $input.first();
const headers = item.json.headers || {};
const signature = String(headers['x-signature'] || '');
const timestamp = String(headers['x-timestamp'] || '');

const raw = await this.helpers.getBinaryDataBuffer(0, 'data');

const secrets = [
  $env.WEBHOOK_SECRET_CURRENT,
  $env.WEBHOOK_SECRET_PREVIOUS,
].filter(Boolean);

function sign(secret) {
  const hmac = crypto.createHmac('sha256', secret);
  hmac.update(`${timestamp}.`);
  hmac.update(raw);
  return hmac.digest();
}

const received = /^[0-9a-f]{64}$/i.test(signature)
  ? Buffer.from(signature, 'hex')
  : null;

let validSignature = false;
if (received) {
  for (const secret of secrets) {
    if (crypto.timingSafeEqual(received, sign(secret))) {
      validSignature = true;
    }
  }
}

const ageSeconds = Math.abs(Date.now() / 1000 - Number(timestamp));
const fresh = Number.isFinite(ageSeconds) && ageSeconds <= 300;

let reason = 'ok';
if (!received) reason = 'bad_signature_format';
else if (!validSignature) reason = 'signature_mismatch';
else if (!fresh) reason = 'stale_timestamp';

return [{
  json: {
    valid: validSignature && fresh,
    reason,
    dedupeKey: `wh:${signature.toLowerCase()}`,
  },
}];
```

What this code does and why:

- **It validates the format first.** A signature that is not 64 hex characters is rejected before any comparison, which also guarantees both buffers have the same length. `timingSafeEqual` throws an error if the lengths differ.
- **It hashes bytes, not text.** The timestamp and the raw buffer are fed to the HMAC separately, so a body that is not valid UTF-8 text is still handled correctly.
- **It compares in constant time.** `timingSafeEqual` takes the same time whether the first or the last byte differs, so an attacker cannot learn the signature one character at a time from response times.
- **It tries both secrets.** During rotation, requests signed with either the current or the previous secret pass.
- **It returns a reason code.** You can log `reason` internally without ever telling the caller why the request failed.

On self-hosted n8n, a Code node can only use the built-in `crypto` module if your instance allows it (the `NODE_FUNCTION_ALLOW_BUILTIN` setting). If it does not, use the **Crypto** node with the HMAC action, and compare the result with an **IF** node. The IF comparison is not constant-time, so prefer the Code node when you can.

### Step 4: Reject invalid requests early

Add an **IF** node that checks `valid` is true. Connect the false branch to a **Respond to Webhook** node with response code `401` and an empty or generic body. Do not say whether the signature, the timestamp or the secret was wrong, because that helps an attacker. Keep the reason code for your own logs.

### Step 5: Detect duplicate requests

On the true branch, record the signature so the same request cannot be accepted twice. If you use the Redis node, the **Increment** operation with an expiry is a simple option, because incrementing is atomic:

- **Key:** the `dedupeKey` value from the Code node
- **Expire:** on, with a TTL of 600 seconds (twice the timestamp window)

The node returns the new counter value. If it is `1`, this is the first time you have seen the request and the workflow continues. If it is higher than `1`, connect the branch to a **Respond to Webhook** node with response code `409` and stop. Check how the Redis node in your n8n version names its output field.

Only valid signatures are stored, so an attacker sending garbage cannot fill your Redis memory.

### Step 6: Run your workflow and respond

After the checks, run the real workflow. If it takes a long time, respond with `200` right after the duplicate check and let the rest run in the background. The sender then does not time out and retry, which would create duplicates. For risky actions, add a [human approval step](/articles/n8n-ai-agent-tutorial-tools-memory-human-approval) before the workflow does anything that is hard to undo.

## Sign and send a test request

You need a sender that follows the same rules. Any language with HMAC-SHA256 works. Here are two ways to produce a correct request for testing.

### Shell (openssl and curl)

```bash
TS=$(date +%s)
BODY='{"event":"test","id":1}'
SIG=$(printf '%s.%s' "$TS" "$BODY" | openssl dgst -sha256 -hmac "$WEBHOOK_SECRET_CURRENT" -hex | sed 's/^.* //')

curl -i -X POST "$WEBHOOK_URL" \
  -H "Content-Type: application/json" \
  -H "X-Timestamp: $TS" \
  -H "X-Signature: $SIG" \
  -d "$BODY"
```

### Node.js sender

```javascript
import crypto from 'node:crypto';

const body = JSON.stringify({ event: 'test', id: 1 });
const timestamp = Math.floor(Date.now() / 1000).toString();
const signature = crypto
  .createHmac('sha256', process.env.WEBHOOK_SECRET_CURRENT)
  .update(`${timestamp}.${body}`)
  .digest('hex');

const res = await fetch(process.env.WEBHOOK_URL, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-Timestamp': timestamp,
    'X-Signature': signature,
  },
  body,
});
console.log(res.status);
```

Save it as a `.mjs` file so the top-level `await` works. The sender must send exactly the string it signed. If a library or proxy changes the body (for example by re-formatting JSON or compressing it), the signature will not match.

## Replay protection in depth

A valid signature proves the request was created by someone with the secret. It does not prove the request is new. Two controls work together:

1. **Timestamp window.** The timestamp is part of the signed text, so an attacker cannot change it. A captured request becomes useless once it is older than five minutes.
2. **Duplicate detection.** Inside the window, a repeated request has the same signature as the original, because the timestamp and the body are the same. Storing the signature with an expiry of twice the window catches it.

Why use the signature as the key? It is unique for each timestamp and body combination, so you do not need a separate request ID header that an attacker could change. (If you do add a request ID, include it in the signed text, otherwise it is not protected.)

Decide what happens if Redis is unavailable. **Failing closed** (reject requests) is safer for payments or account changes. **Failing open** (accept them) keeps a low-risk workflow running. Pick one on purpose and write it down.

Duplicate detection is not the same as idempotency. Even with both controls, design the workflow so running the same action twice does not cause harm, for example by using the sender's event ID when you create records. For failure handling around this, see [self-healing n8n workflows](/articles/self-healing-n8n-workflows-error-handling-retries-alerts).

If you do not run Redis, workflow static data can store recent signatures for small, low-volume workflows. It only persists for production executions and is not designed for high traffic.

## Rotate secrets without downtime

Rotation is easy when the workflow already accepts two secrets:

1. Generate a new secret, for example with `openssl rand -hex 32`.
2. Move the old value into `WEBHOOK_SECRET_PREVIOUS` and put the new value in `WEBHOOK_SECRET_CURRENT`. Restart or reload n8n so it picks up the variables.
3. Update the sender to sign with the new secret.
4. Wait longer than the timestamp window, then confirm in your logs that no requests still use the old secret.
5. Empty `WEBHOOK_SECRET_PREVIOUS`.

Rotate immediately if a secret appears in a screenshot, ticket, chat or repository, and whenever someone with access leaves the project. Use a different secret for each sender, so one leak never exposes every integration.

## Add limits at the proxy layer

n8n is not a rate limiter. If you run it behind Nginx, put request and size limits in front of it. This is a starting point, not a final configuration. Adjust the numbers to your real traffic:

```nginx
limit_req_zone $binary_remote_addr zone=webhooks:10m rate=10r/s;

server {
    listen 443 ssl;
    server_name n8n.example.com;

    location /webhook/ {
        limit_req zone=webhooks burst=20 nodelay;
        client_max_body_size 256k;
        proxy_pass http://127.0.0.1:5678;
        proxy_set_header Host $host;
    }

    # Production servers rarely need the editor test URL exposed
    location /webhook-test/ {
        return 404;
    }
}
```

Other proxy-level habits:

- Serve webhooks over HTTPS only.
- Allow only the HTTP method your sender uses.
- Avoid logging request headers that contain signatures, or keep those logs short-lived.
- Make sure no CDN, WAF or proxy rewrites the body. Compression, re-formatting or character-set changes break the signature.

These limits reduce load and noise. They do not replace the signature check. If your handler logic grows past what a visual workflow handles comfortably, [moving a WhatsApp bot from n8n to FastAPI](/articles/whatsapp-chatbot-n8n-to-fastapi-migration) shows what that migration looked like.

## Monitor and alert on rejected requests

A rejected request is information. Add a branch after each rejection that records:

- the reason code (`bad_signature_format`, `signature_mismatch`, `stale_timestamp`, `duplicate`)
- the time and the webhook path
- the source IP address, if your policy allows storing it

Do not store the body, the secret or the full signature. Then watch for patterns:

- A sudden rise in `signature_mismatch` can mean probing, or a sender using an old secret after rotation.
- Many `stale_timestamp` results from one sender usually mean clock drift or queued retries.
- Many `duplicate` results can mean a sender retrying too aggressively.

Send alerts through an n8n error workflow or your normal monitoring tool. If a flood is hurting production, you also want a fast way to switch the endpoint off, which is the idea behind an [AI agent kill switch](/articles/ai-agent-kill-switch-guide-crowdstrike).

## Test with good and bad requests

Do not trust the setup until every case behaves as expected. Run these against the **production URL** of an active workflow and watch the executions in n8n.

| Test case | How to produce it | Expected result |
|---|---|---|
| Valid request | Sign and send normally | Workflow runs, `200` |
| Wrong signature | Change one character of the signature | `401`, no later nodes run |
| Missing headers | Leave out `X-Signature` or `X-Timestamp` | `401` |
| Stale timestamp | Use a timestamp 10 minutes old and sign it correctly | `401` |
| Duplicate | Send the exact same request twice within five minutes | First `200`, second `409` |
| Tampered body | Sign one body, send a different body | `401` |

After the run, open the n8n executions list. Rejected requests should stop at the IF node or the Respond node. Only the valid request should reach the real workflow. Keep a screenshot of one accepted and one rejected execution as evidence for your own records.

## Common mistakes

1. **Signing parsed JSON** instead of the raw body, so the signature breaks whenever formatting changes.
2. **Forgetting to enable Raw Body** on the Webhook node.
3. **Comparing with `===` or `==`** instead of a constant-time function.
4. **Hard-coding the secret** in a node and then exporting or sharing the workflow.
5. **Returning detailed errors** that tell attackers which check failed.
6. **Testing only the test URL**, then discovering the production URL behaves differently.
7. **Not testing the stale and duplicate cases**, which are the ones people forget.
8. **Using one secret for every sender**, so a single leak exposes everything.
9. **Letting a proxy or CDN alter the body**, which makes valid requests fail.

## When to use the vendor's own scheme

If the sender is a third-party service, follow its signing rules instead of inventing your own. GitHub, for example, signs the raw body and sends the result in an `X-Hub-Signature-256` header with a `sha256=` prefix. The header name, the signed text, the encoding and the timestamp rules all differ between vendors, so read the vendor documentation and adapt the Code node to match it.

## Production checklist

- Raw Body is enabled on the Webhook node
- Secrets live in environment variables or a secret store, one per sender
- The signature check is the first node after the Webhook node
- Comparison is constant-time and the format is validated first
- Timestamps older than five minutes are rejected
- Duplicate signatures are rejected, and the failure mode for Redis is decided
- Rejected requests return `401` or `409` with no details
- Rejection reasons are logged without secrets or bodies
- Rate and body-size limits are set at the proxy, and `/webhook-test/` is not exposed
- Rotation steps are written down and tested
- You tested all six cases against the production URL

## Frequently asked questions

### Is a secret webhook URL enough?

No. URLs leak through logs, screenshots and shared files, and a URL proves nothing about who is calling. Use signature verification as well.

### Should I use Basic Auth or header auth instead?

If the sender cannot sign requests, header or Basic auth is better than nothing. HMAC is stronger because it also proves the body was not changed, and because the secret itself is never sent over the network.

### Does HMAC encrypt my data?

No. It proves who sent the request and that the body is unchanged. Always use HTTPS so the data is encrypted in transit.

### Which hash algorithm should I use?

SHA-256 is a sound default and is supported everywhere. Avoid MD5 and SHA-1 for new designs.

### What if the sender cannot compute HMAC at all?

Use header authentication with a long random token, restrict by IP address if the sender has fixed addresses, and rate limit at the proxy. Treat it as a weaker setup and keep the workflow's actions low-risk.

### Will this slow down my workflow?

The check is one hash calculation and a comparison, so the cost is small compared with network calls and AI model requests. Measure it in your own executions if latency matters.

### Do I need Redis?

Not for the signature check. Redis (or another store) is only needed for duplicate detection. Small, low-risk workflows can rely on the timestamp window alone, but anything that moves money or changes records should detect duplicates.

*Need secure automations built for your stack? [Get in touch](/contact).*
