Send sign-up events to analytics and CRM
Tell Segment, Mixpanel, Amplitude, PostHog, Salesforce or HubSpot when a person signs up or signs in.
What it shows
- You connect an analytics destination in the portal, and choose the events that it receives. A CRM connection writes a contact for each new account.
- A person signs up. The destination receives
user.registered, with a pseudonym in place of the user ID. - For a tool that has no connector, a webhook sends
user.createdanduser.loginto a small forwarder of your own. - The forwarder checks the signature, answers at once, and sends the tool one small event with the user ID.
Before you start
- The permission
settings.managein the portal for the connectors. - An account at the destination: Segment, Mixpanel, Amplitude or PostHog for analytics, HubSpot or Salesforce for the CRM.
- Check that your plan includes analytics export and CRM sync in the plans matrix. The webhook path needs neither.
- For the forwarder: a public HTTPS address where it runs, and the inbound address of your tool. An API key with the scopes
admin:webhooks:readandadmin:webhooks:writecreates the webhook.
| Variable | Value |
|---|---|
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 | For webhook.sh: an API key with the scopes admin:webhooks:read and admin:webhooks:write. |
WEBHOOK_URL | For webhook.sh: the public HTTPS address of the deployed forwarder, for example https://hooks.example.com/webhooks. |
SECRET_FILE | Optional, for webhook.sh. The file that receives the answer of the creation, with the signing secret. Default: ~/lumoauth-forwarder.json. |
LUMOAUTH_WEBHOOK_SECRET | The forwarder reads it: the signing secret of the webhook. Set it with export LUMOAUTH_WEBHOOK_SECRET=$(jq -r .data.secret ~/lumoauth-forwarder.json). |
FORWARD_URL | The inbound address of your tool, which receives one JSON event for each sign-up and sign-in. |
FORWARD_TOKEN | Optional. A token that the forwarder sends to the tool as Authorization: Bearer. |
PORT | Optional. The port of the forwarder. Default: 3000. |
Connect an analytics destination
- Open Integrations in the portal, and go to the section Analytics, CDP & CRM.
- Click Configure on the card of your tool, for example Segment. The page Segment opens.
- Enter the credential, for example the Write key, and choose the Data region.
- Under Events to forward, tick
user.registeredanduser.login. With none ticked, every event of the list is forwarded. - Leave Send identify calls (email & name) off, unless your agreement with the tool covers names and addresses.
- Turn on Enable Segment, click Save configuration, then Send test event.
Connect a CRM
- In the same section, click Configure on the card of HubSpot or Salesforce.
- Enter the credentials, for example the Private app access token for HubSpot.
- Under What to sync, keep Contacts on user registration on.
- Turn on the sync, for example Enable HubSpot sync, click Save configuration, then Test connection.
These steps were written from the docs. Nobody has followed them for this page yet. The connector steps were not followed: they need an account at an analytics tool or a CRM.
Code
webhook.sh creates the webhook for the forwarder and saves its signing secret. forward.mjs is the forwarder.
Run each command from the recipes folder of the examples repository. Set the folder up once for your language. The connector steps were not followed: they need an account at an analytics tool or a CRM.
- Node.js
- lumo CLI
// Forward sign-ups and sign-ins to a tool that has no LumoAuth connector.
// The receiver checks the signature of each webhook, answers at once, and
// then sends a small event to the inbound address of the tool.
//
// node operations/analytics-and-crm/js/forward.mjs
import { createHmac, timingSafeEqual } from 'node:crypto';
import express from 'express';
const secret = process.env.LUMOAUTH_WEBHOOK_SECRET;
const forwardUrl = process.env.FORWARD_URL;
const port = Number(process.env.PORT ?? 3000);
if (!secret || !forwardUrl) {
console.error('Set LUMOAUTH_WEBHOOK_SECRET and FORWARD_URL.');
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.
const seen = new Set();
/** Checks one signature header. Returns the delivery ID, or null. */
function verify(header, rawBody) {
if (!header) 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;
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;
}
/**
* What the tool receives. The person is named by the LumoAuth user ID. A
* sign-up also carries the email address, which a CRM needs for a contact.
* Nothing else of the webhook leaves your server.
*/
function toolEvent(event, envelope) {
const data = envelope.data;
switch (event) {
case 'user.created':
// The new account is the target of the event.
return { type: 'signed_up', user_id: data.target_id, email: data.metadata?.email ?? data.target_name, at: envelope.timestamp };
case 'user.login':
// The person who signed in is the actor of the event.
return { type: 'signed_in', user_id: data.actor_id, method: data.metadata?.method ?? null, at: envelope.timestamp };
default:
return null;
}
}
async function forward(item) {
const headers = { 'Content-Type': 'application/json' };
// Many tools put their token in the inbound address. Others want a header.
if (process.env.FORWARD_TOKEN) headers.Authorization = `Bearer ${process.env.FORWARD_TOKEN}`;
const answer = await fetch(forwardUrl, { method: 'POST', headers, body: JSON.stringify(item) });
return answer.status;
}
const app = express();
// express.raw keeps the bytes of the body, which the signature covers.
app.post('/webhooks', express.raw({ type: 'application/json' }), (req, res) => {
// For 24 hours after a rotation, the second header holds a signature that
// was made with the secret from before the rotation.
const deliveryId =
verify(req.get('X-LumoAuth-Signature'), req.body) ?? verify(req.get('X-LumoAuth-Signature-Previous'), req.body);
if (!deliveryId) {
console.log('rejected: no valid signature');
return res.status(401).json({ error: 'invalid_signature' });
}
const event = req.get('X-LumoAuth-Event');
// A repeat is answered with 200 too, so that LumoAuth stops sending it.
if (seen.has(deliveryId)) {
console.log(`${event}: repeat, not forwarded`);
return res.json({ received: true });
}
seen.add(deliveryId);
// Answer first: LumoAuth waits 5 seconds, then counts the delivery as failed.
res.json({ received: true });
const item = toolEvent(event, JSON.parse(req.body.toString('utf8')));
if (!item) return console.log(`${event}: not forwarded`);
forward(item)
.then((status) => console.log(`${event} -> ${item.type} ${item.user_id}: the tool answered ${status}`))
.catch((error) => console.log(`${event} -> ${item.type} ${item.user_id}: not delivered (${error.message})`));
});
app.listen(port, '127.0.0.1', () => console.log(`listening on http://localhost:${port}/webhooks`));
node operations/analytics-and-crm/js/forward.mjs
Compiles. Not run against an organization. The forwarder ran locally against deliveries that were signed with the documented scheme, in the shape of real user.created and user.login events, and it sent them to a local stand-in for the tool. No delivery from an organization reached it: the test organization had no public receiver.
#!/bin/sh
# Create the webhook that sends sign-ups and sign-ins to the forwarder.
#
# sh operations/analytics-and-crm/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 the deployed forwarder.
: "${WEBHOOK_URL:?Set WEBHOOK_URL, for example https://hooks.example.com/webhooks}"
# 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-forwarder.json}"
# Look for a webhook with this address first: a second one would forward
# 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 user.created,user.login > "$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
lumo webhooks get "$WEBHOOK_ID" -o json | jq -r '.data | "events: \(.events | join(" ")), active: \(.isActive)"'
sh operations/analytics-and-crm/cli/webhook.sh
Run against a LumoAuth organization.
Check the result
listening on http://localhost:3000/webhooks
user.created -> signed_up 01a22000-bbaf-7256-b895-a33a8bdb4ab4: the tool answered 202
user.login -> signed_in 01a22000-bbaf-7256-b895-a33a8bdb4ab4: the tool answered 202
- The tool receives
{"type": "signed_up", "user_id": "…", "email": "…", "at": "…"}for a sign-up, and{"type": "signed_in", "user_id": "…", "method": "password", "at": "…"}for a sign-in. No event carries a password, a token or the signing secret. - At an analytics destination, the event is
user.registeredoruser.login. Itsdistinct_idis a pseudonym that is stable for the person, not the user ID. - In HubSpot or Salesforce, the new person is a contact, found by the email address.
- The portal shows sent and failed counters and the last error on the page of each connector.
Limits
- An analytics destination receives a fixed list of events. Other audit events are never forwarded.
- The CRM gets a contact only for an account that a person creates: by sign-up, by accepting an invitation, or at the first sign-in with a social or SAML connection. Accounts that an administrator, the Admin API, SCIM, HR sync or LDAP creates are not sent.
- The forwarder handles
user.createdfor every new account, however it was created. Filter on the event data if your tool wants only sign-ups. - A webhook sends no event about a person whose processing is restricted under GDPR, except
user.deleted. - The forwarder keeps the delivery IDs in memory. With more than one instance, keep them in a store that all instances share.