Security Guide

Authentication Methods

Secure your N8.Chat webhooks with proper authentication to prevent unauthorized access and protect your AI workflows.

Important Security Notice

Without proper authentication, anyone with your webhook URL can send requests to your n8n workflow, potentially causing unwanted API costs and exposing sensitive data. Always secure your webhooks in production.

API Key Authentication

The most common and recommended method is to use a custom API key sent in the request headers. This is simple to implement and works with both n8n cloud and self-hosted instances.

1. Generate a Secure API Key

Create a strong, random API key. You can use a password generator or run one of these commands:

Linux/macOS:

openssl rand -hex 32

PowerShell:

[Convert]::ToBase64String((1..32 | ForEach-Object {Get-Random -Maximum 256}) -as [byte[]])

This generates a cryptographically secure random string

2. Configure N8.Chat to Send the API Key

In your N8.Chat plugin settings, add a custom header with your API key:

Header Name

X-API-Key

Header Value

your_secret_api_key_here

3. Validate the API Key in n8n

Add an IF node after your webhook to validate the API key:

IF Node Configuration:

Condition:{{ $json.headers['x-api-key'] }}
Operation:equals
Value:{{ $env.N8CHAT_API_KEY }}

Connect the true branch to your AI nodes, and the false branch to a Respond to Webhook node that returns an error:

{
  "success": false,
  "error": "Unauthorized",
  "message": "Invalid or missing API key"
}

Webhook Security

Additional security measures to protect your webhook endpoints beyond API key authentication.

HMAC Signature Verification

For enhanced security, use HMAC signatures to verify that requests are coming from your N8.Chat instance and haven not been tampered with.

  1. 1.N8.Chat creates a signature by hashing the request body with a shared secret
  2. 2.The signature is sent in the X-Webhook-Signature header
  3. 3.Your n8n workflow verifies the signature matches the expected value

n8n Function Node - Signature Verification:

const crypto = require('crypto');

const secret = $env.WEBHOOK_SECRET;
const signature = $json.headers['x-webhook-signature'];
const body = JSON.stringify($json.body);

const expectedSignature = 'sha256=' + crypto
  .createHmac('sha256', secret)
  .update(body)
  .digest('hex');

if (signature === expectedSignature) {
  return [{ json: { valid: true, ...items[0].json } }];
} else {
  throw new Error('Invalid webhook signature');
}

Request Timestamp Validation

Prevent replay attacks by validating the request timestamp is within an acceptable window:

const requestTimestamp = parseInt($json.headers['x-request-timestamp']);
const currentTime = Math.floor(Date.now() / 1000);
const maxAge = 300; // 5 minutes

if (Math.abs(currentTime - requestTimestamp) > maxAge) {
  throw new Error('Request timestamp too old or in future');
}

return [{ json: { ...items[0].json, timestampValid: true } }];

IP Allowlisting

If your server has a static IP, you can restrict webhook access to specific IP addresses:

const allowedIPs = ['203.0.113.50', '198.51.100.25'];
const clientIP = $json.headers['x-forwarded-for'] || $json.headers['x-real-ip'];

if (!allowedIPs.includes(clientIP)) {
  throw new Error('IP address not allowed: ' + clientIP);
}

return [{ json: { ...items[0].json, ipValid: true } }];

User Authentication

Identify and authenticate individual users interacting with the chat widget.

User Data in Requests

When a logged-in user sends a chat message, N8.Chat includes user data in the webhook payload:

{
  "message": "What's my order status?",
  "user": {
    "id": "user_12345",
    "email": "customer@example.com",
    "name": "John Doe",
    "role": "customer"
  },
  "session": {
    "id": "sess_abc123xyz",
    "started_at": "2025-01-15T10:00:00Z"
  },
  "context": {
    "page_url": "https://example.com/my-account/orders",
    "page_title": "My Orders",
    "referrer": "https://example.com/checkout"
  }
}

WordPress Users

User data is automatically populated from WordPress when users are logged in. Includes user ID, display name, email, and roles.

Shopify Customers

Shopify customer data is included when customers are logged in to their accounts. Includes customer ID, email, and name.

Guest Users

For guest users, a unique session ID is generated and maintained across the conversation. No personal data is sent.

Custom Authentication

Use the JavaScript API to pass custom user data from your own authentication system.

Session Management

N8.Chat maintains conversation sessions to provide context-aware responses and track conversation history.

Session Lifecycle

1

Session Creation

A new session is created when a user first opens the chat widget

2

Session Persistence

Sessions persist across page navigations using localStorage

3

Session Expiry

Sessions expire after 30 minutes of inactivity (configurable)

4

Session Renewal

Each message resets the session timeout

Maintaining Conversation History

Use the session ID to store and retrieve conversation history in n8n:

// In n8n, use a database or cache to store history
const sessionId = $json.session.id;
const message = $json.message;

// Retrieve existing history (from Redis, database, etc.)
const history = await getConversationHistory(sessionId);

// Add new message to history
history.push({ role: 'user', content: message });

// Send to AI with full context
const response = await callAI(history);

// Save updated history
history.push({ role: 'assistant', content: response });
await saveConversationHistory(sessionId, history);

return response;

Security Best Practices

Always Use HTTPS

Never send API keys or sensitive data over unencrypted HTTP connections

Rotate Keys Regularly

Change your API keys every 90 days or immediately if compromised

Use Environment Variables

Store secrets in n8n environment variables, never hardcode in workflows

Implement Rate Limiting

Limit requests per IP/session to prevent abuse and control costs

Validate User Input

Always sanitize and validate user messages before processing

Monitor and Audit

Log all webhook requests and set up alerts for suspicious activity

Authentication Headers Reference

Reference table for common authentication header patterns used with N8.Chat:

Header NamePurposeExample Value
X-API-KeySimple API key authenticationa1b2c3d4e5f6...
AuthorizationBearer token authenticationBearer eyJhbGc...
X-Webhook-SignatureHMAC signature verificationsha256=abc123...
X-Session-IDUser session identificationsess_xyz789abc
X-Request-TimestampReplay attack prevention1705312200

Testing Your Authentication

Use curl to test your webhook authentication from the command line:

Valid Request (should succeed):

curl -X POST https://your-n8n-instance.com/webhook/n8chat \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your_secret_api_key" \
  -d '{"message": "Hello, this is a test"}'

Invalid Request (should fail with 401):

curl -X POST https://your-n8n-instance.com/webhook/n8chat \
  -H "Content-Type: application/json" \
  -H "X-API-Key: wrong_key" \
  -d '{"message": "This should be rejected"}'