Skip to main content
Version: v0.31.0

Authenticate requests with an API key

Every OpenWA REST route is protected by an API key sent in the X-API-Key header. This guide shows you how to send that key, how a key's role and scope decide what it can do, and how to mint, inspect, and revoke keys through the API.

Prerequisites

Send the key on every request​

Authenticate by adding the X-API-Key header to each request. The base URL in these examples is http://localhost:2785/api (the /api global prefix on the default port 2785); in production, OpenWA sits behind your own domain and TLS.

curl http://localhost:2785/api/sessions \
-H "X-API-Key: YOUR_API_KEY"

A successful call returns the resource:

[
{ "id": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a", "name": "my-bot", "status": "ready", "createdAt": "2026-06-25T09:30:00.000Z" }
]

Replace YOUR_API_KEY with a real key — a full key looks like owa_k1_ followed by 64 hex characters. Add Content-Type: application/json only when you send a request body. The same key authenticates the JS SDK:

import { OpenWAClient } from "@rmyndharis/openwa";

const client = new OpenWAClient({
baseUrl: "http://localhost:2785",
apiKey: "YOUR_API_KEY",
});

const sessions = await client.sessions.list();
Bearer also works

OpenWA accepts the key as Authorization: Bearer YOUR_API_KEY in addition to X-API-Key. Use X-API-Key as the canonical form so every example on this site stays consistent.

WebSocket handshake no longer accepts ?apiKey=

A key in the URL leaks into proxy and access logs, so the Socket.IO handshake no longer accepts the ?apiKey= query string. Connect with the key in the auth.apiKey field (recommended) or send the X-API-Key header instead. The gateway serves one namespace, /events, so point the client at <host>/events: a client aimed at the bare origin is refused since v0.26.0 (Invalid namespace). Before, it landed on Socket.IO's default namespace, which was unauthenticated, carried no events and sat outside the handshake and per-key limits below.

import { io } from "socket.io-client";

// Recommended: key in the auth field
const socket = io("http://localhost:2785/events", { auth: { apiKey: "YOUR_API_KEY" } });

// Alternative: key in a header
const socket = io("http://localhost:2785/events", {
extraHeaders: { "X-API-Key": "YOUR_API_KEY" },
});

Rejected WebSocket authentication attempts are audited with the same api_key_auth_failed event the REST guard emits, so credential probing over the WebSocket surface leaves a forensic trail. Since v0.25.0, chat-restricted keys can connect and subscribe within their chat scope. A subscribe that discovers an invalid key or changed chat authorization is also audited before the socket closes. Since v0.27.0 the gateway closes the connection on any refused handshake or when a subscribe finds the key is no longer valid, and when the key store cannot be read it answers INTERNAL_ERROR instead of UNAUTHORIZED (closing on handshake, keeping the socket open on subscribe so the client can retry). A session-scope refusal keeps the socket open.

WebSocket connections are rate-limited

The gateway bounds the WebSocket surface with three independent limits: a per-IP handshake window (10 per 60 s by default; since v0.23.6 an IPv6 client is counted on its /64) charged before authentication and refunded once the handshake proves authentic — it bounds failed handshakes without letting clients behind one NAT shut each other out; a per-key cap of 16 simultaneous sockets; and a per-key frame token bucket (60 frames/s, 120-frame burst). A handshake over the per-IP window, or a connection over the key's socket cap, is answered with a RATE_LIMITED error frame and closed. A frame over the bucket is answered with a RATE_LIMITED error frame and not processed, and the socket stays open. Each kind of violation writes a rate_limit_exceeded audit row, sampled to one per minute per kind and subject. Before v0.23.6 a handshake whose connection dropped while its key was still being validated kept one of the key's socket slots until the gateway restarted (or the key's sockets were closed by a revoke or authorization change), so a client on an unstable network could use up the cap and have every new connection refused with Too many concurrent connections for this API key; since v0.23.6 that slot is released. Since v0.26.0 a client frame over 8 KiB also closes the connection; subscribe, unsubscribe and ping frames are under 1 KB. Tune the limits with WS_RATE_LIMIT_HANDSHAKE_MAX, WS_RATE_LIMIT_HANDSHAKE_WINDOW_MS, WS_MAX_SOCKETS_PER_KEY, WS_RATE_LIMIT_FRAME_PER_SECOND, and WS_RATE_LIMIT_FRAME_BURST (see Configuration for their defaults and parsing).

The first admin key​

On its first boot, when no keys exist yet, OpenWA seeds one admin key. It is printed to the startup log and written to data/.api-key (mode 0600; /app/data/.api-key in Docker). On later restarts the log shows only a masked fingerprint. The full key stays in that file; the dashboard lists only each key's 12-character prefix.

The file tracks the key, not the other way around: OpenWA validates it against the stored key's hash at boot and on the revoke and delete paths, and removes it once its key no longer validates. The one exception is a changed API_KEY_PEPPER — a key row still carries the file's prefix but the hash no longer matches. The file then survives and a startup WARN names the repair: restore the original pepper, or clear the api_keys table and restart to seed a new admin key.

Use this admin key to mint scoped, lower-privilege keys for your integrations, then keep the admin key for management only. If you set API_MASTER_KEY in your environment, OpenWA seeds that value instead of a random one and writes it to data/.api-key, while since v0.28.0 it is omitted from the startup banner and its keyPrefix in key listings is (master key) instead of the first 12 characters — see Configuration.

Recover a lost admin key​

A key cannot be recovered from its hash. First read the bootstrap file (cat data/.api-key, docker compose exec openwa-api cat /app/data/.api-key, or kubectl exec openwa-0 -- cat /app/data/.api-key). It has no trailing newline; copy only the key. It can manage keys only while active, unexpired, admin, without session/chat scope and accessible from your allowed IP. Changing API_MASTER_KEY does not replace an existing key. If another usable admin exists, mint a replacement and revoke the lost key through the API.

With no usable admin left, replace one key row while preserving other credentials:

  1. Stop the instance and back up its main database, MAIN_DATABASE_NAME (data/main.sqlite by default). Use the gateway install directory holding dist/ and data/. If the service manager provides API_KEY_PEPPER, export that exact value into the recovery shell too.

  2. Generate the new key, prefix and hash with the installed gateway's hash function and configuration:

    GEN="require('./dist/config/load-env'); const key = 'owa_k1_' + require('crypto').randomBytes(32).toString('hex'); console.log('key:', key); console.log('prefix:', key.slice(0, 12)); console.log('hash:', require('./dist/modules/auth/api-key-hash').hashApiKey(key, process.env.API_KEY_PEPPER))"
    node -e "$GEN"
    # Compose alternative, with the service stopped:
    docker compose run --rm --no-deps openwa-api node -e "$GEN"
  3. Read the admin rows, then update only the chosen row using its ID and the generated values:

    sqlite3 data/main.sqlite "SELECT id, name, keyPrefix, isActive, expiresAt FROM api_keys WHERE role = 'admin'"
    sqlite3 data/main.sqlite "UPDATE api_keys SET keyHash = '<hash>', keyPrefix = '<prefix>', isActive = 1, expiresAt = NULL, allowedIps = NULL, allowedSessions = NULL, allowedChats = NULL WHERE id = '<id>'"

    For Compose, run each SQL statement through docker compose run --rm --no-deps openwa-api sqlite3 /app/data/main.sqlite "...". Use your configured main database path if different.

  4. Restart and authenticate with the generated key. The old key stops working. This also clears that row's expiry, revoked state and restrictions; narrow it through the API after regaining access.

For Helm, generate the values before scaling down, inside the existing pod (kubectl exec openwa-0 -- node -e "$GEN"), which carries the release's Secret and exact pepper. Then scale the StatefulSet to zero and start the restore helper described in the tagged restore runbook, which mounts the PVC at /app/data (the runbook names the pod openwa-restore). Copy the database out first with kubectl cp openwa-restore:/app/data/main.sqlite ./main.sqlite.bak, then run the SQL against /app/data/main.sqlite on the PVC itself, for example with kubectl exec openwa-restore -- sqlite3 /app/data/main.sqlite "...". The helper's /restore directory is an emptyDir that goes away with the pod, so do not keep the only copy there. Delete the helper before restoring the StatefulSet to one replica.

If no key row is worth preserving, an offline DELETE FROM api_keys makes the next boot seed an admin key from API_MASTER_KEY (or a random key), but every other credential must be reissued. Prefer replacing one row. If a pepper change invalidated all keys, restore the original pepper or reset and reissue every key. Recovery affects only this node's main database.

Roles​

Every key carries exactly one role. Roles are hierarchical — a higher role satisfies any route that requires a lower one, so an admin key passes an operator-guarded route.

RoleRankCan do
viewer1Read routes: list sessions, read messages, view contacts and groups. Not every read is open to it. For example, search, the webhook, automation-rule and template lists, group invite codes, contact number checks, contact LID lookups (GET .../contacts/{number}/lid, v0.27.1+) and the session QR need operator, and the reads in the admin row need admin.
operator2Everything viewer can, plus write and action routes — send messages, manage groups, manage webhooks.
admin3Everything, plus admin-only routes and mounts — API-key management, runtime settings (GET /api/settings; the PUT was removed in v0.19.0), the audit log (GET /api/audit), the webhook delivery-failure log and its redrive (GET /api/webhooks/delivery-failures, POST /api/webhooks/delivery-failures/redrive), the instance-wide stats aggregates (GET /api/stats/overview and /api/stats/messages), plugin management (/api/plugins), integration instances and redrive (/api/integration/*), session egress proxy changes (PATCH /api/sessions/{sessionId}/proxy, and proxyUrl when creating a session; admin since v0.24.0), the infrastructure routes (/api/infra/*, apart from the public /api/infra/health probe), and the queue dashboard mount (/api/admin/queues).

When role is omitted at creation, the key defaults to operator.

A key whose role is below what a route requires gets 403 Forbidden. This is distinct from 401 Unauthorized, which means the key itself was missing, invalid, revoked, or expired. Since v0.24.0, a valid key outside its allowedIps or allowedSessions scope gets 403. A key restricted with allowedChats (v0.23.6+) is refused with 403 instead, because chat scope is checked after the role; see Scope a key to chats and Errors.

Scope a key to sessions and IPs​

Beyond its role, a key can be narrowed so it works only for certain sessions or from certain source IPs. Both fields are optional; an empty or absent list means "no restriction" for that dimension.

FieldTypeEffect
allowedSessionsstring[]Session ids the key may touch. A scoped key acts only on these sessions; list endpoints return only their data.
allowedIpsstring[]Allowlist of exact IPs and CIDR ranges (for example 203.0.113.50, 10.0.0.0/8).

Scope is enforced during key validation, before the role check. Since v0.24.0, a request that names a session outside the key's allowlist, or comes from an IP outside it, is rejected with 403 Forbidden, even if the role would otherwise permit it. A non-empty allowedIps fails closed: if the client IP can't be determined, the request is also rejected.

The session allowlist also fences integration instance management, whose scope travels in the request body rather than the route. Instance create, patch, and redrive intersect the requested and persisted session scope with your key's allowlist: an instance outside it answers 404 Not Found — indistinguishable from a missing one, so out-of-scope instances cannot be probed — and a scoped key cannot create an all-sessions instance (an omitted or '*' sessionScope). Since v0.26.0 a scoped key's instance changes no longer retire the plugin's all-sessions activation, which an unrestricted key set; before, they could silence the plugin on sessions the scoped key cannot see.

Trust your proxy chain

The client IP is taken from the socket unless the request arrives from a host listed in TRUSTED_PROXIES, in which case X-Forwarded-For is honored. If you run OpenWA behind a reverse proxy and use allowedIps, set TRUSTED_PROXIES so the real client IP is resolved. See Configuration.

Scope a key to chats​

Since v0.23.6 a key can also carry allowedChats, an allowlist of the chats it may reach: groups and individual contacts. It is independent of allowedSessions, so a key can be limited to sessions, to chats, to both, or to neither. An omitted or empty list means every chat. Use it to hand an integration on a shared account a key that reaches only its own groups or conversations.

EntryExample
Group120363021234567890@g.us
Contact by phone628123456789@c.us, the same number as 628123456789@s.whatsapp.net, or the bare number 628123456789 (stored as 628123456789@c.us); every form matches the same contact
Contact by privacy id123456789012345@lid

A group id may also take the legacy <a>-<b>@g.us form, a contact's number or privacy id has at least five digits, and a :<device> suffix is accepted and ignored for matching. A malformed entry, surrounding whitespace, a comma or a duplicate in the array is a 400. The list accepts at most 2000 entries; a longer list is a 400. Only a bare number is rewritten on save; every other entry is stored, and read back, as sent.

A chat-scoped key is denied by default. Every REST route that requires a key answers it with 403 Forbidden unless the route is explicitly marked as open to such a key, and that default also covers routes added in later releases. The public routes skip the REST guard, so chat scope never applies there and they answer as usual: the health checks (/api/health, /api/health/live, /api/health/ready and /api/infra/health), /api/metrics (gated by METRICS_TOKEN, not a key) and the plugin ingress endpoints under /api/ingress. GET /api/health still accepts a chat-scoped key and adds version to its body, as it does for any valid key. On a marked route the guard checks every chat the request names (a {chatId}, {groupId} or {contactId} path parameter, a ?chatId= query, the chatId, fromChatId and toChatId body fields, and each messages[].chatId of a bulk send) and answers 403 when any of them is outside the allowlist. The open routes, all under /api/sessions/{sessionId} except built-in global search (GET /api/search), are:

  • the session itself, GET /api/sessions/{sessionId}, so an integration can tell whether it is connected (use it, not the session list, to test a new chat-scoped key);
  • the chat, group, contact and label-chat lists (GET .../chats, .../groups, .../contacts and .../labels/{labelId}/chats), filtered to allowed chats before pagination; stored messages (GET .../messages) with a required, allowed ?chatId=; and built-in global search, scoped before pagination and totals (plugin search providers refuse these keys);
  • the chat actions under .../chats (read, unread, archive, mute, pin, delete, typing, and clearing a chat's messages) and presence (POST .../presence/subscribe, GET .../presence/{chatId});
  • every send route under .../messages, including send-bulk, reply, forward and click-button, plus POST .../messages/send-product; the message actions (react, delete, vote, pin, unpin, star, edit); and the per-chat reads GET .../messages/{chatId}/history, .../{chatId}/{messageId}/reactions, and .../{chatId}/{messageId}/receipts (v0.28.0+; all three whatsapp-web.js only, Baileys answers 501) and .../{chatId}/{messageId}/media;
  • one contact under .../contacts/{contactId}: read, update, delete, profile picture, phone, block and unblock;
  • a group's detail, settings, subject, description, member label (PUT .../member-label, Baileys only, v0.27.0+) and picture, and leaving it;
  • a chat's labels under .../labels/chat/{chatId}.

Everything else refuses the key: session discovery and statistics, contact number checks, contact LID lookups (GET .../contacts/{number}/lid, v0.27.1+), group creation and joining, participant changes, membership requests, invite codes, the label catalogue (list, get, create or update, and delete), webhooks, automation rules, status, channels, the status and cancel routes of a bulk batch, and POST /api/auth/validate, so such a key cannot sign in to the dashboard. A quotedMessageId is refused with 403 on every route except POST .../messages/reply, which resolves the quote inside the chat it sends to. The role check still applies first, so a chat-scoped viewer key reaches only the open reads.

Contacts are matched through the lid_mappings table: a phone entry also admits the same person's @lid privacy id once the table maps the two, and a @lid entry admits the mapped phone. Since v0.26.0 a mapping counts only once an engine has reported the pair: one inherited from an older release or from a backup without report-origin data, or learned only from a cached lookup, is display data and admits nothing until an engine reports it again, so after the upgrade a phone entry admits a contact's @lid chat only after that report. While the database cannot be read, the match falls back to the gateway's in-memory mappings, which do not see a mapping another gateway node has changed since: a key limited to a number whose privacy id was re-mapped there keeps reaching the chat of that id until the database answers again. When an engine reports a second @lid for a phone number that lid_mappings already maps to another reported @lid (for example after a number is reassigned), the gateway logs a warning and writes a WARN audit row phone_second_lid_reported under the reporting session (v0.27.0+). An entry that names the chat's own id still matches without a mapping. An unmapped @lid matches only a literal @lid entry, and a lid's digits are never read as a phone number, so 555000111@lid does not admit 555000111@c.us.

The chat check runs after key validation and the role check. A valid key outside its session or IP scope answers 403 first (since v0.24.0). Since v0.25.0, the /events WebSocket delivers only allowed chat events (expanding allowedChats through lid_mappings with a 5-second cache per session and allowlist since v0.28.0) and MCP tools enforce the same chat fence as REST; see WebSockets and MCP. The Bull Board queue dashboard still refuses chat-restricted keys with 403. Changing allowedChats disconnects the key's live sockets; reconnect and subscribe again.

The API accepts allowedChats on an admin key too, but no admin-only route is open to a chat-scoped key, and the last usable admin cannot be given a chat scope. Since v0.24.0 the dashboard can set and display allowedChats for operator and viewer keys. For an admin key, use POST /api/auth/api-keys or PUT /api/auth/api-keys/{id}.

Earlier releases ignore allowedChats

Only v0.23.6 and later enforce allowedChats. An earlier release does not read it, so a chat-scoped key on a node rolled back to one has the full reach of its role and session scope. Keys live in each node's own main database; repeat key changes on every node. Issue chat-scoped keys only once every node runs v0.23.6 or later, and revoke them before rolling back without restoring the pre-upgrade auth database. With MAIN_DATABASE_SYNCHRONIZE at its default, an earlier release also drops the allowedChats column when it boots, so the allowlists do not come back with the next upgrade. See Roll back a bad migration.

Manage keys​

API keys are managed under /api/auth/api-keys. Every management route requires an admin key with no session scope: a key carrying an allowedSessions allowlist is rejected with 403 Forbidden on every route in this controller, whatever its role, and the denial lands in the same api_key_auth_failed audit trail as any other rejected request. Since v0.23.6 a key carrying allowedChats is refused there with 403 as well.

Scoped admin keys can no longer manage keys — breaking in v0.11.0

Before v0.11.0 a session-scoped admin key could mint an unrestricted admin key, clear another key's scope, or enumerate every credential — a total, persistent escape from its fence. That path is closed. If one of your integrations manages keys with a scoped admin key, move it to an unrestricted admin key; unrestricted keys, including the bootstrap key, are unaffected.

The plaintext key is shown once

A new key's full plaintext value is returned only in the creation response, under apiKey. Store it securely right away — it is hashed at rest and cannot be retrieved later. List and get responses return only keyPrefix (the first 12 characters, for example owa_k1_01234, or (master key) for a key seeded from API_MASTER_KEY since v0.28.0), never the full key.

Create a key​

POST /api/auth/api-keys

FieldTypeRequiredNotes
namestringYesFriendly label, 3 to 100 characters; a name outside that range is a 400.
role"admin" | "operator" | "viewer"NoDefaults to operator.
allowedIpsstring[]NoIP / CIDR allowlist.
allowedSessionsstring[]NoAllowlist of session ids (the generated UUIDs, not names). Matched by exact equality against the id in the request path, so a name silently scopes the key to nothing. Since v0.23.4 each entry must be non-empty, free of surrounding whitespace and free of commas, and the array must hold no duplicates; anything else is a 400.
allowedChatsstring[]NoChat ids (v0.23.6+), at most 2000 since v0.25.0: groups, contacts by @c.us, @s.whatsapp.net or @lid id, or bare phone numbers. Refused with 400 for a malformed entry, surrounding whitespace, a comma or a duplicate. See Scope a key to chats.
expiresAtstring (ISO 8601)NoKey stops validating after this time.

When sent, allowedIps, allowedSessions and allowedChats must each be a JSON array (omitted or null leaves the list unset). Since v0.26.0 an object sent for any of them (for example { "628123456789@c.us": true }) is refused with 400 on create and on PUT. Before, it was stored as an empty list, which means no restriction, so the key reached every chat, session or address.

An empty allowedSessions entry used to mean the opposite of scoping

The column stores a comma join and reads back with a comma split, so two shapes did not survive the round trip and both failed open. allowedSessions: [""] joined to an empty string, read back as [], and every enforcement site treats a zero-length list as every session: a request that looked like a scoping landed as a widening. ["a,b"] read back as two separate entries, so the stored allowlist was not the one sent. Since v0.23.4 both are refused with 400, along with padded entries and duplicates.

An omitted allowedSessions, or a genuinely empty array, still means an unscoped key. That is unchanged and is the intended way to say "every session".

curl -X POST http://localhost:2785/api/auth/api-keys \
-H "X-API-Key: YOUR_ADMIN_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Production Bot",
"role": "operator",
"allowedIps": ["203.0.113.50", "10.0.0.0/8"],
"allowedSessions": ["8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a"],
"expiresAt": "2027-12-31T23:59:59Z"
}'

The 201 Created response carries the one-time plaintext key in apiKey:

{
"id": "3f2a1c9e-1b2d-4a5f-9c8e-aa11bb22cc33",
"name": "Production Bot",
"keyPrefix": "owa_k1_01234",
"role": "operator",
"allowedIps": ["203.0.113.50", "10.0.0.0/8"],
"allowedSessions": ["8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a"],
"isActive": true,
"expiresAt": "2027-12-31T23:59:59.000Z",
"usageCount": 0,
"createdAt": "2026-06-25T09:30:00.000Z",
"apiKey": "owa_k1_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
}

Copy apiKey now. Every later response for this key omits it and returns only keyPrefix.

List, get, update, revoke, delete​

OperationRequestResult
List all keysGET /api/auth/api-keys200 array of keys (no plaintext).
Get one keyGET /api/auth/api-keys/{id}200 single key.
Update mutable fieldsPUT /api/auth/api-keys/{id}200 updated key.
Revoke (deactivate)POST /api/auth/api-keys/{id}/revoke200, sets isActive: false.
Delete permanentlyDELETE /api/auth/api-keys/{id}204 No Content.

Since v0.23.6 the create, list, get, update and revoke responses carry allowedChats when the key has a chat allowlist, in its stored form (a bare number reads back as <number>@c.us); the field is omitted for a key without one.

PUT accepts the same fields as create (all optional): name, role, allowedIps, allowedSessions, allowedChats, expiresAt. Send only the fields you want to change; an omitted allowedChats is left as it is, and an empty array clears it. A role of null changes no role: since v0.31.0 it no longer counts as a demotion, so it does not answer 409 on the last usable admin by itself. To replace a key's IP allowlist, PUT it with the new allowedIps array:

curl -X PUT http://localhost:2785/api/auth/api-keys/3f2a1c9e-1b2d-4a5f-9c8e-aa11bb22cc33 \
-H "X-API-Key: YOUR_ADMIN_KEY" \
-H "Content-Type: application/json" \
-d '{ "allowedIps": ["203.0.113.50"] }'

To take a key out of service, revoke rather than delete it — revoke flips isActive to false (the key then fails with 401) while keeping the record:

curl -X POST http://localhost:2785/api/auth/api-keys/3f2a1c9e-1b2d-4a5f-9c8e-aa11bb22cc33/revoke \
-H "X-API-Key: YOUR_ADMIN_KEY"
{
"id": "3f2a1c9e-1b2d-4a5f-9c8e-aa11bb22cc33",
"name": "Production Bot",
"keyPrefix": "owa_k1_01234",
"role": "operator",
"isActive": false,
"usageCount": 412,
"createdAt": "2026-06-25T09:30:00.000Z"
}

Use DELETE only when you want the record gone entirely.

Revoking or deleting a key, or changing its role, allowedIps, allowedSessions, allowedChats or expiresAt, closes its live /events sockets with an UNAUTHORIZED frame. A rename and usage-counter updates leave them connected. The node handling the request closes them immediately; a minute sweep also catches expiry, direct writes to that node's database and connections racing a change. Each node keeps its own auth database, so repeat authorization changes on every node. A key whose stored expiresAt no longer parses counts as expired: REST answers 401, and since v0.26.0 the sweep also closes its sockets with API key has expired.

The frame names the cause: API key has been revoked, API key has been deleted, API key has expired or API key authorization changed; please reconnect. Reconnect and resubscribe with a currently valid key. Chat scope itself no longer prevents a handshake in v0.25.0; an IP restriction excluding the client still does.

The last usable admin is protected

OpenWA refuses — with 409 Conflict — any operation that would strip the last usable admin: demoting, revoking, deleting, or expiring it, or applying a session scope or (since v0.23.6) a chat scope to it. A usable admin is an active, unexpired admin key with no session scope and no allowedChats. A session-scoped admin can authenticate but can never manage keys, so counting it as a survivor would bless a lockout with no in-band recovery. The check and the mutation share one lock, so two concurrent requests cannot race past the guard.

Key operations are audited

Creating, updating, deleting, and revoking a key each write an api_key_created / api_key_updated / api_key_deleted / api_key_revoked audit entry with the acting admin key, the client IP, and the target key; an update also records the key's role, restrictions and expiry before and after. A failed authentication (invalid, disabled/expired, IP- or session-scope-denied, chat-scope-denied, a scoped key on a key-management route, or insufficient role) writes an api_key_auth_failed entry with the client IP, method, path, and reason. Two further actions cover throttling and the queue dashboard: rate_limit_exceeded when the /events WebSocket refuses a handshake over the per-IP window, a connection over the per-key socket cap, or a frame over the frame bucket (no other rate limit writes this action) — sampled to one row per minute per kind and subject, so the audit writes themselves cannot become the flood — and queue_board_mutated for every authenticated non-GET request to the Bull Board queue dashboard, whose 401/403 rejections now also write the standard api_key_auth_failed row. Audit logging is best-effort and never affects the request outcome. Review entries through GET /api/audit or the dashboard Logs page.

Check a key with /auth/validate​

Any valid key can confirm its own validity and resolve its role, except a key restricted with allowedChats (v0.23.6+): this route is not open to a chat-scoped key, so such a key gets 403 Forbidden here, and client.auth() fails with the same 403. This is the quickest way to test that a key works and to read its role from a client.

POST /api/auth/validate

curl -X POST http://localhost:2785/api/auth/validate \
-H "X-API-Key: YOUR_API_KEY"
{ "valid": true, "role": "operator", "engineType": "baileys", "scoped": false }

engineType reports the instance engine; since v0.24.0 scoped reports whether the key has a non-empty session allowlist. A missing or invalid key returns 401 Unauthorized rather than { "valid": false }, because the global guard rejects it before this handler runs. The call does not double-count key usage, and an IP-restricted key validates correctly (a valid IP-pinned key is no longer reported as invalid). The SDK wraps the same call:

const { valid, role } = await client.auth();
// { valid: true, role: "operator" }

Authorize Swagger UI​

The bundled Swagger UI uses the same X-API-Key scheme. It is served at /api/docs outside production unless ENABLE_SWAGGER=false, and in production only with ENABLE_SWAGGER=true; the published image and the full docker-compose.yml run in production, so enable it there first (see Expose or hide Swagger in production). Click Authorize, paste your key, and every "Try it out" request carries it. There is no separate token: it is the same key you send with curl or the SDK, except for GET /api/metrics, which takes the METRICS_TOKEN bearer shown as a second scheme in the dialog.

Errors​

StatusWhenFix
401 UnauthorizedKey missing, invalid, revoked (isActive: false), or expired.Send a valid, active key. Check expiresAt.
403 ForbiddenSince v0.24.0, a valid key outside allowedIps or allowedSessions; also a key whose role rank is below the route's requirement (for example a viewer key on a send route, any non-admin key on /api/auth/api-keys, or, since v0.24.0, a key below admin that sets a session proxy with proxyUrl on create or PATCH /api/sessions/{sessionId}/proxy), or a session-scoped key on a deployment-global surface (key management, /api/infra, most of /api/plugins, /api/settings, the instance-wide /api/stats reads, POST /api/sessions, and PATCH /api/sessions/{sessionId}/proxy). Since v0.23.6 also a key carrying allowedChats on a route not open to it, on a chat outside its allowlist, or with a quotedMessageId anywhere but the reply route.For a chat-scoped key, stay on the open routes and its own chats. Otherwise use a key with a sufficient role, and no session scope on those surfaces, or raise the key's role with PUT.
404 Not FoundThe {id} in a management route does not match an existing key.List keys to find the correct id.

Since v0.24.0 session and IP scope violations return 403; earlier releases returned 401. Missing, unknown, revoked and expired keys still return 401. Deployment-global surfaces also reject session-scoped keys with 403, because those routes have no session parameter to constrain. The set is:

  • the whole key-management controller, /api/auth/api-keys (otherwise a scoped key could mint an unrestricted one);
  • all of /api/infra (config, data export and import, status, storage);
  • most of /api/plugins, including install, update, enable and per-plugin configuration;
  • /api/settings and the two instance-wide /api/stats reads;
  • POST /api/sessions, since the new session is outside the caller's allowlist by construction;
  • PATCH /api/sessions/{sessionId}/proxy (v0.23.4+), since routing a session's egress through a chosen host is an instance-level decision.

Each refusal is written to the same api_key_auth_failed audit trail.

Chat scope (v0.23.6+) is the other 403 case. It is checked after the key has authenticated, so a route not open to a chat-scoped key, or a chat outside allowedChats, answers 403 rather than 401. The message tells the cases apart: API key is restricted to selected chats when the route is not open to the key (or a quotedMessageId is sent anywhere but the reply route), and API key not authorized for this chat when a chat the request names is outside the allowlist. Two more name a single route: chatId is required for a key restricted to selected chats (v0.24.0+) when GET .../messages is called without a ?chatId=, and Chat-restricted search requires the built-in search provider (v0.25.0+) when a plugin search provider answers GET /api/search. On an open route the chat check can also answer a chat-scoped key with 400, before the body is validated: when a chat field is present but is not a single string (<field> must be a single chat id string), or when a bulk send's messages is not an array or holds more than 100 entries.

Next steps​