Verify Ory webhooks
Ory doesn't sign Actions webhooks, so there's no signature to check and no SDK to verify one. An api_key credential sends a value you generate in a header you name, and your endpoint compares it in constant time. That authenticates the sender, but it doesn't protect the body or stop a replay.
These pages cover Ory Actions webhooks, whose body you write in a template. Ory's live event streams, for enterprise contracts, are a separate feature that sends named events such as IdentityCreated to an HTTPS endpoint or AWS SNS.
The facts
Ory webhook secret
Ory issues no secret. You generate a value and set it in the action's authentication settings. Keep it in an environment variable, not in source code.
-
nameis the header,valueis the key, andinplaces it in aheaderor acookie. All three are mandatory - Ory sends the value as written, so a
Bearerprefix you typed is part of what you compare -
basic_authtakesuserandpasswordinstead, and sends HTTP Basic
Source: Ory docs ↗
Code
// Generated with: ory-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config({ quiet: true });
const crypto = require('crypto');
const express = require('express');
const app = express();
// Ory lets you pick the HTTP method for each action, so accept all the useful ones.
const ALLOWED_METHODS = ['GET', 'POST', 'PUT', 'PATCH'];
/**
* Constant-time string comparison. Hashing both sides first gives equal-length
* buffers, so timingSafeEqual never throws and the secret's length isn't leaked.
*/
function safeEqual(a, b) {
const ha = crypto.createHash('sha256').update(String(a)).digest();
const hb = crypto.createHash('sha256').update(String(b)).digest();
return crypto.timingSafeEqual(ha, hb);
}
/**
* Ory does not sign webhooks. With auth.type api_key (in: header) it sends
* `<name>: <value>`, both chosen by you. Compare the WHOLE header value, including any
* "Bearer " prefix you typed. A static credential authenticates the sender, not the
* body, and gives no replay protection.
*/
function verifyOryRequest(
headers,
secret = process.env.ORY_WEBHOOK_SECRET,
headerName = process.env.ORY_WEBHOOK_HEADER || 'Authorization'
) {
if (!secret) return false; // never accept when unconfigured
const received = headers[headerName.toLowerCase()]; // Node lowercases header names
return Boolean(received) && safeEqual(received, secret);
}
function handleEvent(payload) {
// `event` comes from YOUR Jsonnet template; these names are the illustrative ones.
const { event, identity } = payload;
const id = identity && identity.id;
switch (event) {
case 'registration.after':
console.log(`Identity registered: ${id}`);
// Your code: add the user to your CRM or newsletter
break;
case 'login.after':
console.log(`Identity logged in: ${id}`);
// Your code: record the sign-in
break;
case 'settings.after':
console.log(`Identity updated settings: ${id}`);
// Your code: sync updated traits
break;
case 'verification.after':
console.log(`Identity verified an address: ${id}`);
// Your code: mark the address as verified downstream
break;
case 'recovery.after':
console.log(`Identity recovered account: ${id}`);
// Your code: notify the user
break;
default:
console.log(`Unhandled event: ${event}`);
}
}
// Read the body raw (any content type) so the request is authenticated before parsing.
app.all('/webhooks/ory', express.raw({ type: '*/*' }), (req, res) => {
if (!ALLOWED_METHODS.includes(req.method)) {
return res.status(405).set('Allow', ALLOWED_METHODS.join(', ')).json({ error: 'Method not allowed' });
}
if (!verifyOryRequest(req.headers)) {
return res.status(401).json({ error: 'Invalid or missing webhook credential' });
}
// The body is optional (a GET action has none).
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 Ory event:', err);
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.verifyOryRequest = verifyOryRequest;
if (require.main === module) {
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/ory`);
});
} // Generated with: ory-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { verifyOryRequest } from '../../../lib/verify-ory';
interface OryPayload {
event?: string;
identity?: { id?: string; [key: string]: unknown };
[key: string]: unknown;
}
function handleEvent(payload: OryPayload): void {
// `event` comes from YOUR Jsonnet template; these names are the illustrative ones.
const { event, identity } = payload;
const id = identity?.id;
switch (event) {
case 'registration.after':
console.log(`Identity registered: ${id}`);
// Your code: add the user to your CRM or newsletter
break;
case 'login.after':
console.log(`Identity logged in: ${id}`);
// Your code: record the sign-in
break;
case 'settings.after':
console.log(`Identity updated settings: ${id}`);
// Your code: sync updated traits
break;
case 'verification.after':
console.log(`Identity verified an address: ${id}`);
// Your code: mark the address as verified downstream
break;
case 'recovery.after':
console.log(`Identity recovered account: ${id}`);
// Your code: notify the user
break;
default:
console.log(`Unhandled event: ${event}`);
}
}
// Ory lets you pick the HTTP method for each action, so one handler serves several.
async function handler(request: NextRequest) {
// Authenticate before reading or parsing the body.
if (!verifyOryRequest(request.headers)) {
return NextResponse.json({ error: 'Invalid or missing webhook credential' }, { status: 401 });
}
// The body is optional (a GET action has none). Read as text so any content type works.
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 OryPayload);
} catch (err) {
console.error('Error handling Ory event:', err);
return NextResponse.json({ error: 'Handler error' }, { status: 500 });
}
return NextResponse.json({ received: true });
}
export { handler as GET, handler as POST, handler as PUT, handler as PATCH }; # Generated with: ory-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hmac
import json
import os
from dotenv import load_dotenv
from fastapi import Depends, FastAPI, HTTPException, Request
load_dotenv()
app = FastAPI()
def safe_equal(a: str, b: str) -> bool:
"""Constant-time comparison. Encode both sides: compare_digest raises TypeError on
non-ASCII str, but accepts any bytes."""
return hmac.compare_digest(a.encode("utf-8"), b.encode("utf-8"))
def verify_ory_request(headers, secret=None, header_name=None) -> bool:
"""Ory does not sign webhooks. With auth.type api_key (in: header) it sends
`<name>: <value>`, both chosen by you. Compare the WHOLE header value, including any
"Bearer " prefix you typed. A static credential authenticates the sender, not the
body, and gives no replay protection.
"""
secret = secret if secret is not None else os.environ.get("ORY_WEBHOOK_SECRET")
header_name = header_name or os.environ.get("ORY_WEBHOOK_HEADER") or "Authorization"
if not secret:
return False # never accept when unconfigured
received = headers.get(header_name) # Starlette headers are case-insensitive
return bool(received) and safe_equal(received, secret)
async def require_ory_credential(request: Request) -> None:
"""FastAPI dependency: reject the request before the body is parsed."""
if not verify_ory_request(request.headers):
raise HTTPException(status_code=401, detail="Invalid or missing webhook credential")
def handle_event(payload: dict) -> None:
# `event` comes from YOUR Jsonnet template; these names are the illustrative ones.
event = payload.get("event")
identity = payload.get("identity")
identity_id = identity.get("id") if isinstance(identity, dict) else None
if event == "registration.after":
print(f"Identity registered: {identity_id}")
# Your code: add the user to your CRM or newsletter
elif event == "login.after":
print(f"Identity logged in: {identity_id}")
# Your code: record the sign-in
elif event == "settings.after":
print(f"Identity updated settings: {identity_id}")
# Your code: sync updated traits
elif event == "verification.after":
print(f"Identity verified an address: {identity_id}")
# Your code: mark the address as verified downstream
elif event == "recovery.after":
print(f"Identity recovered account: {identity_id}")
# Your code: notify the user
else:
print(f"Unhandled event: {event}")
# Ory lets you pick the HTTP method for each action, so accept the useful ones.
@app.api_route(
"/webhooks/ory",
methods=["GET", "POST", "PUT", "PATCH"],
dependencies=[Depends(require_ory_credential)],
)
async def ory_webhook(request: Request):
# Read the raw body so any content type is accepted. The body is optional (GET has none).
raw_body = await request.body()
payload: object = {}
if raw_body.strip():
try:
payload = json.loads(raw_body)
except (json.JSONDecodeError, UnicodeDecodeError):
raise HTTPException(status_code=400, detail="Invalid JSON body")
if not isinstance(payload, dict):
raise HTTPException(status_code=400, detail="Expected a JSON object")
try:
handle_event(payload)
except Exception as err: # noqa: BLE001
print(f"Error handling Ory event: {err}")
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 Ory webhooks skill:
npx skills add hookdeck/webhook-skills --skill ory-webhooks
Common failures
Prefix left out of the comparison
Ory sends the value as written. If you typed Bearer abc, the value to compare is Bearer abc, not abc.
Header name mismatch
name in auth.config sets the header. Your endpoint has to read the same name, and header names are case-insensitive.
Key placed in a cookie
With in: cookie, the key isn't in a header at all. Use in: header.
The action uses basic_auth
basic_auth sends HTTP Basic credentials in Authorization, not your value as written, so a direct comparison fails. Switch the action to api_key.
From Hookdeck's Ory guide
Let Event Gateway check the Ory key.
Give your Ory source the same header name and the whole value you set on the action. Event Gateway compares it on each request before it reaches your service, then queues requests and retries failures on your schedule. An api_key in a cookie or basic_auth can't be checked by this source type.