Receive webhooks
Handle events from LumoAuth in your backend: verify the signature, answer fast, and survive a repeat.
What it shows
- A receiver reads the body of the request as bytes, and checks the HMAC signature and the time of the signature.
- The receiver answers with 200 at once, and does its work after the answer.
- The receiver remembers the ID of each delivery, so a delivery that arrives twice is handled once.
- While you develop,
lumo tunnelforwards the events of your organization to the receiver on your laptop. - For the deployed receiver, the CLI creates the webhook, sends a test event, and rotates the signing secret.
The receiver is the same in Express, FastAPI and Go. It uses the framework and the standard library only: the signature is plain HMAC-SHA256.
Before you start
- The lumo CLI and
jq, for the scripts of the CLI tab. - An API key with the scopes
admin:webhooks:readandadmin:webhooks:write. Create it in the portal under Applications & developer tools, API keys. - For the last step, a receiver at a public HTTPS address. LumoAuth refuses a webhook that points at
localhostor at a private network. On your laptop, use the tunnel.
| Variable | Value |
|---|---|
LUMOAUTH_WEBHOOK_SECRET | The receiver reads it: the signing secret of the webhook. webhook.sh saves the answer of the creation, so set it with export LUMOAUTH_WEBHOOK_SECRET=$(jq -r .data.secret ~/lumoauth-webhook.json). |
ALLOW_UNSIGNED | Set it to 1 only on your laptop, while lumo tunnel forwards the events. The tunnel does not sign. |
PORT | Optional. The port of the receiver. Default: 3000. |
LUMOAUTH_URL | The address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region. |
LUMOAUTH_ORG_ID | Your organization, for example acme-corp. |
LUMOAUTH_API_KEY | The CLI scripts read it: an API key with the scopes admin:webhooks:read and admin:webhooks:write. |
WEBHOOK_URL | For webhook.sh: the public HTTPS address of your deployed receiver, for example https://api.example.com/webhooks. |
WEBHOOK_EVENTS | Optional, for webhook.sh. The events, with commas between them. Default: user.created,user.login. |
WEBHOOK_ID | For rotate.sh: the ID of the webhook. webhook.sh prints it. |
Code
Start a receiver in one terminal, and the tunnel in a second one. Then do something in your organization, for example create a user: the event arrives at the receiver.
Run each command from the recipes folder of the examples repository. Set the folder up once for your language.
- Node.js
- Python
- Go
- lumo CLI
// Receive webhooks from LumoAuth in Express: verify the signature, answer at
// once, and ignore a repeat.
//
// node operations/receive-webhooks/js/receiver.mjs
import { createHmac, timingSafeEqual } from 'node:crypto';
import express from 'express';
const secret = process.env.LUMOAUTH_WEBHOOK_SECRET;
// `lumo tunnel` forwards events to your laptop without a signature. Set
// ALLOW_UNSIGNED=1 only for that, never on a deployed receiver.
const allowUnsigned = process.env.ALLOW_UNSIGNED === '1';
const port = Number(process.env.PORT ?? 3000);
if (!secret && !allowUnsigned) {
console.error('Set LUMOAUTH_WEBHOOK_SECRET, or ALLOW_UNSIGNED=1 for lumo tunnel.');
process.exit(1);
}
// The clocks of two servers differ a little. Five minutes is a common limit.
const MAX_AGE_SECONDS = 300;
// The delivery IDs that were handled. A real app keeps them in a store that
// all its instances share, and removes them after a few days.
const seen = new Set();
/** Checks one signature header. Returns the delivery ID, or null. */
function verify(header, rawBody) {
if (!header || !secret) return null;
// The header is "kid=...,t=<unix time>,id=<delivery ID>,v1=<hex HMAC>".
const fields = Object.fromEntries(
header.split(',').map((field) => {
const at = field.indexOf('=');
return [field.slice(0, at), field.slice(at + 1)];
}),
);
if (!fields.t || !fields.id || !fields.v1) return null;
if (Math.abs(Date.now() / 1000 - Number(fields.t)) > MAX_AGE_SECONDS) return null;
// LumoAuth signs the time, the delivery ID and the body exactly as it was sent.
const expected = createHmac('sha256', secret).update(`${fields.t}.${fields.id}.`).update(rawBody).digest();
const given = Buffer.from(fields.v1, 'hex');
return given.length === expected.length && timingSafeEqual(given, expected) ? fields.id : null;
}
const app = express();
// express.raw keeps the bytes of the body. A signature over parsed JSON
// that was written out again would not match.
app.post('/webhooks', express.raw({ type: 'application/json' }), (req, res) => {
let deliveryId;
if (req.get('X-LumoAuth-Signature')) {
// For 24 hours after a rotation, the second header holds a signature
// that was made with the secret from before the rotation.
deliveryId =
verify(req.get('X-LumoAuth-Signature'), req.body) ??
verify(req.get('X-LumoAuth-Signature-Previous'), req.body);
if (!deliveryId) {
console.log('rejected: the signature does not match');
return res.status(401).json({ error: 'invalid_signature' });
}
} else if (allowUnsigned) {
deliveryId = req.get('X-LumoAuth-Delivery');
} else {
console.log('rejected: no signature');
return res.status(401).json({ error: 'missing_signature' });
}
const event = req.get('X-LumoAuth-Event');
if (seen.has(deliveryId)) {
// A repeat is answered with 200 too, so that LumoAuth stops sending it.
console.log(`${event} ${deliveryId} repeat, ignored`);
return res.json({ received: true });
}
seen.add(deliveryId);
// Answer first: LumoAuth waits 5 seconds, then counts the delivery as failed.
res.json({ received: true });
console.log(`${event} ${deliveryId} accepted`);
setImmediate(() => handle(event, JSON.parse(req.body.toString('utf8'))));
});
/** The work of your app. It runs after the answer. */
function handle(event, body) {
// A delivery from LumoAuth wraps the event: { event, timestamp, tenant, data }.
// The tunnel sends the inner object only.
const data = body.data ?? body;
if (event === 'user.created') console.log(` new user: ${data.target_id}`);
}
app.listen(port, '127.0.0.1', () => console.log(`listening on http://localhost:${port}/webhooks`));
ALLOW_UNSIGNED=1 node operations/receive-webhooks/js/receiver.mjs
Compiles. Not run against an organization. The receiver accepted a webhook.test event of an organization through lumo tunnel, and it verified requests that were signed with the documented scheme. No signed delivery from an organization reached it: the test organization had no public receiver.
"""Receive webhooks from LumoAuth in FastAPI: verify the signature, answer at
once, and ignore a repeat.
python operations/receive-webhooks/python/receiver.py
"""
import hashlib
import hmac
import json
import os
import sys
import time
import uvicorn
from fastapi import BackgroundTasks, FastAPI, Request
from fastapi.responses import JSONResponse
secret = os.environ.get("LUMOAUTH_WEBHOOK_SECRET", "")
# `lumo tunnel` forwards events to your laptop without a signature. Set
# ALLOW_UNSIGNED=1 only for that, never on a deployed receiver.
allow_unsigned = os.environ.get("ALLOW_UNSIGNED") == "1"
port = int(os.environ.get("PORT", "3000"))
if not secret and not allow_unsigned:
sys.exit("Set LUMOAUTH_WEBHOOK_SECRET, or ALLOW_UNSIGNED=1 for lumo tunnel.")
# The clocks of two servers differ a little. Five minutes is a common limit.
MAX_AGE_SECONDS = 300
# The delivery IDs that were handled. A real app keeps them in a store that
# all its instances share, and removes them after a few days.
seen: set[str] = set()
def verify(header: str | None, raw_body: bytes) -> str | None:
"""Checks one signature header. Returns the delivery ID, or None."""
if not header or not secret:
return None
# The header is "kid=...,t=<unix time>,id=<delivery ID>,v1=<hex HMAC>".
fields = dict(field.split("=", 1) for field in header.split(",") if "=" in field)
t, delivery_id, given = fields.get("t"), fields.get("id"), fields.get("v1")
if not t or not delivery_id or not given or not t.isdigit():
return None
if abs(time.time() - int(t)) > MAX_AGE_SECONDS:
return None
# LumoAuth signs the time, the delivery ID and the body exactly as it was sent.
signed = f"{t}.{delivery_id}.".encode() + raw_body
expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
return delivery_id if hmac.compare_digest(given, expected) else None
def handle(event: str, body: dict) -> None:
"""The work of your app. It runs after the answer."""
# A delivery from LumoAuth wraps the event: { event, timestamp, tenant, data }.
# The tunnel sends the inner object only.
data = body.get("data", body)
if event == "user.created":
print(f" new user: {data.get('target_id')}", flush=True)
app = FastAPI()
@app.post("/webhooks")
async def webhooks(request: Request, tasks: BackgroundTasks):
# request.body() gives the bytes of the body. A signature over parsed
# JSON that was written out again would not match.
raw_body = await request.body()
headers = request.headers
if headers.get("X-LumoAuth-Signature"):
# For 24 hours after a rotation, the second header holds a signature
# that was made with the secret from before the rotation.
delivery_id = verify(headers.get("X-LumoAuth-Signature"), raw_body) or verify(
headers.get("X-LumoAuth-Signature-Previous"), raw_body
)
if not delivery_id:
print("rejected: the signature does not match", flush=True)
return JSONResponse({"error": "invalid_signature"}, status_code=401)
elif allow_unsigned:
delivery_id = headers.get("X-LumoAuth-Delivery", "")
else:
print("rejected: no signature", flush=True)
return JSONResponse({"error": "missing_signature"}, status_code=401)
event = headers.get("X-LumoAuth-Event", "")
if delivery_id in seen:
# A repeat is answered with 200 too, so that LumoAuth stops sending it.
print(f"{event} {delivery_id} repeat, ignored", flush=True)
return {"received": True}
seen.add(delivery_id)
# Answer first: LumoAuth waits 5 seconds, then counts the delivery as
# failed. FastAPI runs a background task after it has sent the answer.
print(f"{event} {delivery_id} accepted", flush=True)
tasks.add_task(handle, event, json.loads(raw_body))
return {"received": True}
if __name__ == "__main__":
print(f"listening on http://localhost:{port}/webhooks", flush=True)
uvicorn.run(app, host="127.0.0.1", port=port, log_level="warning")
ALLOW_UNSIGNED=1 python operations/receive-webhooks/python/receiver.py
Compiles. Not run against an organization. The receiver accepted a webhook.test event of an organization through lumo tunnel, and it verified requests that were signed with the documented scheme. No signed delivery from an organization reached it: the test organization had no public receiver.
// Receive webhooks from LumoAuth in net/http: verify the signature, answer at
// once, and ignore a repeat.
//
// go run ./operations/receive-webhooks/go
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
"sync"
"time"
)
var (
secret = os.Getenv("LUMOAUTH_WEBHOOK_SECRET")
// `lumo tunnel` forwards events to your laptop without a signature. Set
// ALLOW_UNSIGNED=1 only for that, never on a deployed receiver.
allowUnsigned = os.Getenv("ALLOW_UNSIGNED") == "1"
// The delivery IDs that were handled. A real app keeps them in a store
// that all its instances share, and removes them after a few days.
seen = map[string]bool{}
seenMu sync.Mutex
)
// The clocks of two servers differ a little. Five minutes is a common limit.
const maxAge = 5 * time.Minute
// verify checks one signature header. It returns the delivery ID, or "".
func verify(header string, rawBody []byte) string {
if header == "" || secret == "" {
return ""
}
// The header is "kid=...,t=<unix time>,id=<delivery ID>,v1=<hex HMAC>".
fields := map[string]string{}
for _, field := range strings.Split(header, ",") {
if name, value, ok := strings.Cut(field, "="); ok {
fields[name] = value
}
}
t, err := strconv.ParseInt(fields["t"], 10, 64)
if err != nil || fields["id"] == "" {
return ""
}
if age := time.Since(time.Unix(t, 0)); age > maxAge || age < -maxAge {
return ""
}
// LumoAuth signs the time, the delivery ID and the body exactly as it was sent.
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(fields["t"] + "." + fields["id"] + "."))
mac.Write(rawBody)
given, err := hex.DecodeString(fields["v1"])
if err != nil || !hmac.Equal(given, mac.Sum(nil)) {
return ""
}
return fields["id"]
}
func webhooks(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "POST only", http.StatusMethodNotAllowed)
return
}
// The bytes of the body. A signature over parsed JSON that was written
// out again would not match.
rawBody, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
if err != nil {
http.Error(w, "body too large", http.StatusRequestEntityTooLarge)
return
}
var deliveryID string
switch {
case r.Header.Get("X-LumoAuth-Signature") != "":
deliveryID = verify(r.Header.Get("X-LumoAuth-Signature"), rawBody)
if deliveryID == "" {
// For 24 hours after a rotation, the second header holds a signature
// that was made with the secret from before the rotation.
deliveryID = verify(r.Header.Get("X-LumoAuth-Signature-Previous"), rawBody)
}
if deliveryID == "" {
fmt.Println("rejected: the signature does not match")
answer(w, http.StatusUnauthorized, `{"error":"invalid_signature"}`)
return
}
case allowUnsigned:
deliveryID = r.Header.Get("X-LumoAuth-Delivery")
default:
fmt.Println("rejected: no signature")
answer(w, http.StatusUnauthorized, `{"error":"missing_signature"}`)
return
}
event := r.Header.Get("X-LumoAuth-Event")
seenMu.Lock()
repeat := seen[deliveryID]
seen[deliveryID] = true
seenMu.Unlock()
if repeat {
// A repeat is answered with 200 too, so that LumoAuth stops sending it.
fmt.Printf("%s %s repeat, ignored\n", event, deliveryID)
answer(w, http.StatusOK, `{"received":true}`)
return
}
// Answer first: LumoAuth waits 5 seconds, then counts the delivery as failed.
answer(w, http.StatusOK, `{"received":true}`)
fmt.Printf("%s %s accepted\n", event, deliveryID)
go handle(event, rawBody)
}
func answer(w http.ResponseWriter, status int, body string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
io.WriteString(w, body)
}
// handle is the work of your app. It runs after the answer.
func handle(event string, rawBody []byte) {
// A delivery from LumoAuth wraps the event: { event, timestamp, tenant, data }.
// The tunnel sends the inner object only.
var body struct {
Data map[string]any `json:"data"`
TargetID string `json:"target_id"`
}
if err := json.Unmarshal(rawBody, &body); err != nil {
return
}
if event == "user.created" {
targetID := body.TargetID
if id, ok := body.Data["target_id"].(string); ok {
targetID = id
}
fmt.Printf(" new user: %s\n", targetID)
}
}
func main() {
if secret == "" && !allowUnsigned {
log.Fatal("Set LUMOAUTH_WEBHOOK_SECRET, or ALLOW_UNSIGNED=1 for lumo tunnel.")
}
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
http.HandleFunc("/webhooks", webhooks)
fmt.Printf("listening on http://localhost:%s/webhooks\n", port)
log.Fatal(http.ListenAndServe("127.0.0.1:"+port, nil))
}
ALLOW_UNSIGNED=1 go run ./operations/receive-webhooks/go
Compiles. Not run against an organization. The receiver accepted a webhook.test event of an organization through lumo tunnel, and it verified requests that were signed with the documented scheme. No signed delivery from an organization reached it: the test organization had no public receiver.
#!/bin/sh
# Forward the events of your organization to a receiver on your laptop.
#
# sh operations/receive-webhooks/cli/tunnel.sh
#
# Start the receiver first, with ALLOW_UNSIGNED=1: the tunnel does not sign.
# The script needs the lumo CLI.
set -eu
# The CLI has its own names for the three values of the recipes.
export LUMO_BASE_URL="$LUMOAUTH_URL" LUMO_ORG="$LUMOAUTH_ORG_ID" LUMO_API_KEY="$LUMOAUTH_API_KEY"
# The tunnel is a temporary webhook for every event. The CLI reads its
# deliveries and posts each one to the local address. Press Ctrl+C to close
# the tunnel: LumoAuth then deletes the temporary webhook.
exec lumo tunnel --to "${RECEIVER_URL:-http://localhost:3000/webhooks}"
#!/bin/sh
# Create the webhook for a deployed receiver, and send it a test event.
#
# sh operations/receive-webhooks/cli/webhook.sh
#
# The script needs the lumo CLI and jq.
set -eu
# The CLI has its own names for the three values of the recipes.
export LUMO_BASE_URL="$LUMOAUTH_URL" LUMO_ORG="$LUMOAUTH_ORG_ID" LUMO_API_KEY="$LUMOAUTH_API_KEY"
# The public HTTPS address of your receiver.
: "${WEBHOOK_URL:?Set WEBHOOK_URL, for example https://api.example.com/webhooks}"
EVENTS="${WEBHOOK_EVENTS:-user.created,user.login}"
# The answer of the creation holds the signing secret, and LumoAuth shows it
# once. Keep the file outside the repository.
SECRET_FILE="${SECRET_FILE:-$HOME/lumoauth-webhook.json}"
# 1. Look for a webhook with this address first: a second creation would make
# a second webhook, and your receiver would get every event twice.
WEBHOOK_ID=$(lumo webhooks list -o json |
jq -r --arg url "$WEBHOOK_URL" '[.data[] | select(.url == $url) | .id][0] // empty')
if [ -z "$WEBHOOK_ID" ]; then
(umask 077 && lumo webhooks create -o json --url "$WEBHOOK_URL" --events "$EVENTS" > "$SECRET_FILE")
WEBHOOK_ID=$(jq -r '.data.id' "$SECRET_FILE")
echo "created: webhook $WEBHOOK_ID"
echo "signing secret: saved in $SECRET_FILE"
else
echo "already there: webhook $WEBHOOK_ID"
fi
# 2. Read the webhook back.
lumo webhooks get "$WEBHOOK_ID" -o json | jq -r '.data | "events: \(.events | join(" "))", "active: \(.isActive)"'
# 3. Send one webhook.test event now. It has the same headers and the same
# signature as any other event. Set SEND_TEST=0 to leave this step out.
if [ "${SEND_TEST:-1}" = "1" ]; then
lumo api POST "/admin/webhooks/$WEBHOOK_ID/test" | jq -r '"test: \(.message // .error)"'
fi
#!/bin/sh
# Give a webhook a new signing secret.
#
# WEBHOOK_ID=42 sh operations/receive-webhooks/cli/rotate.sh
#
# The script needs the lumo CLI and jq.
set -eu
# The CLI has its own names for the three values of the recipes.
export LUMO_BASE_URL="$LUMOAUTH_URL" LUMO_ORG="$LUMOAUTH_ORG_ID" LUMO_API_KEY="$LUMOAUTH_API_KEY"
SECRET_FILE="${SECRET_FILE:-$HOME/lumoauth-webhook.json}"
# The answer holds the new secret, and LumoAuth shows it once. For 24 hours
# each delivery also carries a signature that was made with the old secret,
# so a receiver that still holds the old secret loses no event.
(umask 077 && lumo webhooks update "$WEBHOOK_ID" --rotate-secret -o json > "$SECRET_FILE")
echo "rotated: webhook $(jq -r '.data.id' "$SECRET_FILE")"
echo "signing secret: saved in $SECRET_FILE"
sh operations/receive-webhooks/cli/tunnel.sh
Compiles. Not run against an organization. The tunnel, the creation and the rotation ran against an organization. The test event of webhook.sh was sent through a tunnel only: the test organization had no public receiver.
When the receiver is deployed, run webhook.sh once with its public address. The script stores the answer of LumoAuth, which holds the signing secret, in a file in your home folder. Give the secret to the deployed receiver as LUMOAUTH_WEBHOOK_SECRET, and do not set ALLOW_UNSIGNED there.
Check the result
listening on http://localhost:3000/webhooks
webhook.test 269139cb28c54a5100db88f853c9a586 accepted
webhook.test 269139cb28c54a5100db88f853c9a586 repeat, ignored
rejected: the signature does not match
- The first line after the start is a delivery that the receiver accepted. The same delivery a second time gives "repeat, ignored": LumoAuth sends a delivery again when your receiver did not answer with a 2xx status in 5 seconds.
- A request with a wrong signature, with no signature, or with a signature that is older than five minutes gets the status 401.
lumo webhooks deliveries list <webhook-id>shows each delivery with its status and the status code that your receiver answered. The portal shows the same list under Settings, Integrations, in the tab Webhooks: open the menu of the webhook and select Deliveries.- After
rotate.sh, a receiver that still holds the old secret keeps working for 24 hours. In that time each delivery carries the headerX-LumoAuth-Signature-Previous, which the receiver also checks.
Limits
- The tunnel does not sign what it forwards, and it sends the inner
dataobject without the envelope. The receiver reads the name of the event from the headerX-LumoAuth-Eventfor that reason. - A retry of a delivery repeats the delivery ID. A replay from the deliveries list is a new delivery with a new ID, so the receiver handles it again.
- The receiver keeps the delivery IDs in memory. An app with more than one instance needs a shared store for them.
- LumoAuth does not follow a redirect. An answer with a 3xx status counts as a failed delivery.
- A webhook for Slack, Discord or Microsoft Teams gets a formatted message, not this JSON. See Get alerts for attacks.