Verify Workato webhooks
Workato doesn't sign these requests, so there's no signature to check and no SDK to verify one. With Basic authentication on the HTTP connection, your endpoint compares the username and password from the Authorization header in constant time. That authenticates the sender, but it doesn't protect the body or stop a replay.
These pages cover requests a Workato recipe sends to your endpoint. To send events into Workato and start a recipe, see Workato's Webhooks connector docs.
The facts
Workato webhook secret
You choose the username and password and enter them on the Workato HTTP connection. Workato generates no secret. Keep it in an environment variable, not in source code.
- Enter them when you create the HTTP connection, in the
Basic auth userandBasic auth passwordfields, withAuthentication typeset toBasic. - Keep them in the connection or a secrets manager. Workato says not to hard-code usernames or passwords in the action's input fields.
- The docs don't describe rotation. To change the credentials, update the connection and your stored values together.
Source: Workato docs ↗
Code
// Generated with: workato-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config({ quiet: true });
const crypto = require('crypto');
const express = require('express');
const app = express();
// The request method is chosen in the Workato recipe, so accept all of these.
const METHODS = ['POST', 'PUT', 'PATCH', 'GET', 'DELETE'];
/**
* Constant-time string comparison. Lengths are checked first (equal-length
* buffers are required by timingSafeEqual), then the bytes are compared.
*/
function safeEqual(a, b) {
const ba = Buffer.from(String(a), 'utf8');
const bb = Buffer.from(String(b), 'utf8');
if (ba.length !== bb.length) return false;
return crypto.timingSafeEqual(ba, bb);
}
/**
* Workato has no webhook signature. The recipe's HTTP action uses an HTTP
* connection with Basic auth, which sends:
* Authorization: Basic base64(username:password)
* This is a static shared credential: it authenticates the sender, not the
* body, and gives no replay protection.
*/
function verifyWorkatoRequest(headers, config = process.env) {
const user = config.WORKATO_WEBHOOK_USERNAME;
const password = config.WORKATO_WEBHOOK_PASSWORD;
if (!user || !password) return false; // never accept when unconfigured
const match = (headers['authorization'] || '').match(/^Basic\s+([A-Za-z0-9+/]+={0,2})\s*$/i);
if (!match) return false;
const decoded = Buffer.from(match[1].trim(), 'base64').toString('utf8');
const sep = decoded.indexOf(':'); // the password may itself contain ':'
if (sep === -1) return false;
// Evaluate both comparisons before deciding (no short-circuit).
const userOk = safeEqual(decoded.slice(0, sep), user);
const passwordOk = safeEqual(decoded.slice(sep + 1), password);
return userOk && passwordOk;
}
/**
* Workato has no built-in webhook events: the payload is whatever the recipe's
* HTTP action sends. These examples assume { "event": "...", "data": {...} }.
*/
function handleEvent(payload) {
const { event, data = {} } = payload;
switch (event) {
case 'order.created':
console.log(`Order created: ${data.order_id}`);
// Your code: fulfil the order
break;
case 'record.updated':
console.log(`Record updated: ${data.record_id}`);
// Your code: sync the record
break;
case 'recipe.failed':
console.log(`Recipe failed: ${data.recipe_name} (${data.error})`);
// Your code: alert the owning team
break;
default:
console.log(`Unhandled event: ${event}`);
}
}
// Read the body raw (any content type) so the request is authenticated
// before anything is parsed.
app.all('/webhooks/workato', express.raw({ type: '*/*' }), (req, res) => {
if (!METHODS.includes(req.method)) {
return res.status(405).set('Allow', METHODS.join(', ')).json({ error: 'Method not allowed' });
}
if (!verifyWorkatoRequest(req.headers)) {
return res.status(401).json({ error: 'Invalid or missing credentials' });
}
// GET and DELETE usually have no body; that's fine.
const raw = Buffer.isBuffer(req.body) ? req.body.toString('utf8') : '';
let payload = {};
if (raw.trim() !== '') {
try {
payload = JSON.parse(raw);
} catch {
return res.status(400).json({ error: 'Invalid JSON body' });
}
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
return res.status(400).json({ error: 'Expected a JSON object' });
}
}
try {
handleEvent(payload);
} catch (err) {
console.error('Error handling Workato request:', err);
// A non-2xx stops the job unless a Handle errors step catches it.
return res.status(500).json({ error: 'Handler error' });
}
res.status(200).json({ received: true });
});
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
module.exports = app;
module.exports.verifyWorkatoRequest = verifyWorkatoRequest;
if (require.main === module) {
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Endpoint: ${METHODS.join('|')} http://localhost:${PORT}/webhooks/workato`);
});
} // Generated with: workato-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { verifyWorkatoRequest } from '../../../lib/verify-workato';
/**
* Workato has no built-in webhook events: the payload is whatever the recipe's
* HTTP action sends. These examples assume { "event": "...", "data": {...} }.
*/
interface WorkatoPayload {
event?: string;
data?: Record<string, unknown>;
}
function handleEvent(payload: WorkatoPayload): void {
const { event, data = {} } = payload;
switch (event) {
case 'order.created':
console.log(`Order created: ${data.order_id}`);
// Your code: fulfil the order
break;
case 'record.updated':
console.log(`Record updated: ${data.record_id}`);
// Your code: sync the record
break;
case 'recipe.failed':
console.log(`Recipe failed: ${data.recipe_name} (${data.error})`);
// Your code: alert the owning team
break;
default:
console.log(`Unhandled event: ${event}`);
}
}
async function handle(request: NextRequest) {
// Authenticate before reading or parsing the body.
if (!verifyWorkatoRequest(request.headers)) {
return NextResponse.json({ error: 'Invalid or missing credentials' }, { status: 401 });
}
// GET and DELETE usually have no body; that's fine.
const raw = await request.text();
let payload: unknown = {};
if (raw.trim() !== '') {
try {
payload = JSON.parse(raw);
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
}
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
return NextResponse.json({ error: 'Expected a JSON object' }, { status: 400 });
}
}
try {
handleEvent(payload as WorkatoPayload);
} catch (err) {
console.error('Error handling Workato request:', err);
// A non-2xx stops the job unless a Handle errors step catches it.
return NextResponse.json({ error: 'Handler error' }, { status: 500 });
}
return NextResponse.json({ received: true });
}
// The request method is chosen in the Workato recipe, so accept all of these.
export const POST = handle;
export const PUT = handle;
export const PATCH = handle;
export const GET = handle;
export const DELETE = handle; # Generated with: workato-webhooks skill
# https://github.com/hookdeck/webhook-skills
import base64
import binascii
import hmac
import json
import os
import re
from dotenv import load_dotenv
from fastapi import Depends, FastAPI, HTTPException, Request
load_dotenv()
app = FastAPI()
# The request method is chosen in the Workato recipe, so accept all of these.
METHODS = ["POST", "PUT", "PATCH", "GET", "DELETE"]
def safe_equal(a: str, b: str) -> bool:
"""Constant-time comparison on bytes (compare_digest raises on non-ASCII str)."""
return hmac.compare_digest(a.encode("utf-8"), b.encode("utf-8"))
def verify_workato_request(headers, config=os.environ) -> bool:
"""Workato has no webhook signature. The recipe's HTTP action uses an HTTP
connection with Basic auth, which sends:
Authorization: Basic base64(username:password)
This is a static shared credential: it authenticates the sender, not the
body, and gives no replay protection.
"""
user = config.get("WORKATO_WEBHOOK_USERNAME")
password = config.get("WORKATO_WEBHOOK_PASSWORD")
if not user or not password:
return False # never accept when unconfigured
match = re.match(r"^Basic\s+([A-Za-z0-9+/]+={0,2})\s*$", headers.get("authorization") or "", re.IGNORECASE)
if not match:
return False
try:
decoded = base64.b64decode(match.group(1), validate=True).decode("utf-8")
except (binascii.Error, UnicodeDecodeError):
return False
if ":" not in decoded:
return False
# Split on the first colon (the password may itself contain ':') and
# evaluate both comparisons before deciding (no short-circuit).
req_user, req_password = decoded.split(":", 1)
user_ok = safe_equal(req_user, user)
password_ok = safe_equal(req_password, password)
return user_ok and password_ok
async def require_workato_auth(request: Request) -> None:
"""FastAPI dependency: reject the request before the body is parsed."""
if not verify_workato_request(request.headers):
raise HTTPException(status_code=401, detail="Invalid or missing credentials")
def handle_event(payload: dict) -> None:
"""Workato has no built-in webhook events: the payload is whatever the
recipe's HTTP action sends. These examples assume {"event": "...", "data": {...}}."""
event = payload.get("event")
data = payload.get("data") or {}
if event == "order.created":
print(f"Order created: {data.get('order_id')}")
# Your code: fulfil the order
elif event == "record.updated":
print(f"Record updated: {data.get('record_id')}")
# Your code: sync the record
elif event == "recipe.failed":
print(f"Recipe failed: {data.get('recipe_name')} ({data.get('error')})")
# Your code: alert the owning team
else:
print(f"Unhandled event: {event}")
@app.api_route("/webhooks/workato", methods=METHODS, dependencies=[Depends(require_workato_auth)])
async def workato_webhook(request: Request):
raw_body = await request.body()
# GET and DELETE usually have no body; that's fine.
payload: dict = {}
if raw_body.strip():
try:
parsed = json.loads(raw_body)
except (json.JSONDecodeError, UnicodeDecodeError):
raise HTTPException(status_code=400, detail="Invalid JSON body")
if not isinstance(parsed, dict):
raise HTTPException(status_code=400, detail="Expected a JSON object")
payload = parsed
try:
handle_event(payload)
except Exception as err: # noqa: BLE001
print(f"Error handling Workato request: {err}")
# A non-2xx stops the job unless a Handle errors step catches it.
raise HTTPException(status_code=500, detail="Handler error")
return {"received": True}
@app.get("/health")
async def health():
return {"status": "ok"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) Or install the Workato webhooks skill:
npx skills add hookdeck/webhook-skills --skill workato-webhooks
Common failures
Connection uses another authentication type
None sends no credentials, and Header auth, Query params and the OAuth and AWS types send something other than a Basic username and password. Set Authentication type to Basic.
Credentials changed on one side
Editing the Basic auth user or password on the connection doesn't change your stored values. Update both together.
Password split on the wrong colon
Decode the base64 and split on the first colon only, because a password can contain one.
Credentials missing from the first request
Workato doesn't say whether it sends Basic credentials up front or only after a 401 challenge. Log the headers of a test request to see what arrives.
Let Event Gateway check Workato's Basic credentials.
Event Gateway checks the connection's username and password on each Workato request before it reaches your service, then queues it and retries failures on your schedule.