One organization for each customer
Give each business customer its own members, roles and invitations inside your product.
What it shows
- A company signs up for your product. Your backend creates a customer organization for it, here Northwind Labs.
- The person who signed up has an account already. Your backend adds that account as the owner.
- Your backend invites a colleague by email as an administrator.
- A member signs in, and the access token names the customer organization and the role of the member.
- Your API reads these claims, and serves each customer only its own data.
A customer organization is a group of users inside your LumoAuth organization. All customer organizations share the sign-in methods, the sign-in page and the signing keys of your organization.
Before you start
- An API key with the scopes
admin:users:read,admin:users:writeandadmin:roles:read. Create it in the portal under Applications & developer tools, API keys. - Check that your plan includes the Admin API in the plans matrix. The plan also sets how many customer organizations you can have.
- The account of the person who signed up. The setup script creates it.
- The shell scripts need
jq. The script for the CLI needs the lumo CLI.
| 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 | An API key with the scopes admin:users:read, admin:users:write and admin:roles:read. |
SIGNUP_USER_ID | The ID of the account that becomes the owner of the customer organization. The setup script prints it. |
LUMOAUTH_CLIENT_ID | Only for js/api.mjs: the client ID of the application that your customers sign in to. |
The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.
node b2b/customer-organizations/setup.mjs
setup.mjs
// Creates what the recipe needs: the account of the person who signs up for
// Northwind Labs. Run it again at any time.
//
// node b2b/customer-organizations/setup.mjs
//
// The API key needs the scope admin:users:write.
import { randomBytes } from 'node:crypto';
import { ensure, printEnv } from '../../_lib/admin.mjs';
const email = 'sam.rivera@northwind.example.com';
const user = await ensure('/admin/users', (u) => u.email === email, {
email,
name: 'Sam Rivera',
// In your product the person chooses the password at sign-up.
password: `${randomBytes(18).toString('base64url')}#Aa1`,
emailVerified: true,
});
console.log(`The account ${email} is ready.`);
printEnv({ SIGNUP_USER_ID: user.id });
Code
Each program creates the organization, adds the owner and sends the invitation. The JavaScript tab has a second file, js/api.mjs: an API that reads the claims of the token.
Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization. js/api.mjs was run too: it answered a member of Northwind Labs, and it refused the same token for another customer.
- curl
- Node.js
- lumo CLI
#!/bin/sh
# Create a customer organization, make the person who signed up its owner,
# and invite a colleague as administrator, with curl and jq.
#
# sh b2b/customer-organizations/http/customer.sh
set -eu
SLUG="${CUSTOMER_SLUG:-northwind-labs}"
COLLEAGUE="${COLLEAGUE_EMAIL:-maya.chen@northwind.example.com}"
ORGANIZATIONS="$LUMOAUTH_URL/orgs/$LUMOAUTH_ORG_ID/api/v1/admin/organizations"
api() {
curl --silent --show-error --request "$1" "$ORGANIZATIONS$2" \
--header "X-API-Key: $LUMOAUTH_API_KEY" \
--header "Content-Type: application/json" \
${3:+--data "$3"}
}
# A second run answers 409, because the slug is taken. The next call reads the
# organization in both cases. The slug works in place of the ID in every path.
api POST "" "{\"name\": \"Northwind Labs\", \"slug\": \"$SLUG\"}" > /dev/null
ID=$(api GET "/$SLUG" | jq -r .data.id)
echo "organization: $SLUG ($ID)"
# Every customer organization starts with the roles owner, admin and member.
ROLES=$(api GET "/$SLUG/roles")
OWNER_ROLE=$(printf '%s\n' "$ROLES" | jq '.data[] | select(.slug == "owner") | .id')
ADMIN_ROLE=$(printf '%s\n' "$ROLES" | jq '.data[] | select(.slug == "admin") | .id')
# The person who signed up has an account already, so no invitation is needed.
# A second run answers 409, because the person is a member.
api POST "/$SLUG/members" "{\"userId\": \"$SIGNUP_USER_ID\", \"roleId\": $OWNER_ROLE}" > /dev/null
# The colleague gets an email with a link that works for 7 days. A second run
# sends no second email: LumoAuth limits how often one address is invited.
PENDING=$(api GET "/$SLUG/invitations?status=pending" | jq --arg email "$COLLEAGUE" '[.data[] | select(.email == $email)] | length')
if [ "$PENDING" = 0 ]; then
api POST "/$SLUG/invitations" "{\"email\": \"$COLLEAGUE\", \"roleId\": $ADMIN_ROLE}" > /dev/null
fi
api GET "/$SLUG/members" | jq -r '.data[] | "member: \(.user.email) as \(.role.slug)"'
api GET "/$SLUG/invitations?status=pending" | jq -r '.data[] | "invited: \(.email) as \(.role.slug)"'
echo "portal: $LUMOAUTH_URL/b2b/$LUMOAUTH_ORG_ID/$SLUG/"
sh b2b/customer-organizations/http/customer.sh
// Create a customer organization, make the person who signed up its owner,
// and invite a colleague as administrator.
//
// node b2b/customer-organizations/js/customer.mjs
//
// The SDK packages have no call for customer organizations with a request
// body, so this file calls the Admin API with fetch.
const { LUMOAUTH_URL, LUMOAUTH_ORG_ID, LUMOAUTH_API_KEY, SIGNUP_USER_ID } = process.env;
const slug = process.env.CUSTOMER_SLUG ?? 'northwind-labs';
const colleague = process.env.COLLEAGUE_EMAIL ?? 'maya.chen@northwind.example.com';
const organizations = `${LUMOAUTH_URL}/orgs/${LUMOAUTH_ORG_ID}/api/v1/admin/organizations`;
// `allow` names a status that is fine besides 2xx.
async function api(method, path, body, allow) {
const response = await fetch(organizations + path, {
method,
headers: { 'X-API-Key': LUMOAUTH_API_KEY, 'Content-Type': 'application/json' },
body: body ? JSON.stringify(body) : undefined,
});
const answer = await response.json();
if (!response.ok && response.status !== allow) throw new Error(`${method} ${path}: ${JSON.stringify(answer)}`);
return answer;
}
// A second run answers 409, because the slug is taken. The next call reads the
// organization in both cases. The slug works in place of the ID in every path.
await api('POST', '', { name: 'Northwind Labs', slug }, 409);
const organization = (await api('GET', `/${slug}`)).data;
console.log(`organization: ${organization.slug} (${organization.id})`);
// Every customer organization starts with the roles owner, admin and member.
const roles = (await api('GET', `/${slug}/roles`)).data;
const roleId = (roleSlug) => roles.find((role) => role.slug === roleSlug).id;
// The person who signed up has an account already, so no invitation is needed.
// A second run answers 409, because the person is a member.
await api('POST', `/${slug}/members`, { userId: SIGNUP_USER_ID, roleId: roleId('owner') }, 409);
// The colleague gets an email with a link that works for 7 days. A second run
// sends no second email: LumoAuth limits how often one address is invited.
const pending = (await api('GET', `/${slug}/invitations?status=pending`)).data;
if (!pending.some((invitation) => invitation.email === colleague)) {
await api('POST', `/${slug}/invitations`, { email: colleague, roleId: roleId('admin') });
}
for (const member of (await api('GET', `/${slug}/members`)).data) {
console.log(`member: ${member.user.email} as ${member.role.slug}`);
}
for (const invitation of (await api('GET', `/${slug}/invitations?status=pending`)).data) {
console.log(`invited: ${invitation.email} as ${invitation.role.slug}`);
}
console.log(`portal: ${LUMOAUTH_URL}/b2b/${LUMOAUTH_ORG_ID}/${slug}/`);
// An API of your product that serves each customer its own data. It reads the
// customer organization and the role from the access token.
//
// node b2b/customer-organizations/js/api.mjs
//
// Then call it with the access token of a signed-in member:
//
// curl http://localhost:3001/customers/northwind-labs/invoices -H "Authorization: Bearer $ACCESS_TOKEN"
import express from 'express';
import { verifyAccessToken } from '@lumoauth/agent';
const issuer = `${process.env.LUMOAUTH_URL}/orgs/${process.env.LUMOAUTH_ORG_ID}/api/v1`;
// A token with no resource parameter names the application as its audience.
const audience = process.env.LUMOAUTH_CLIENT_ID;
const invoices = {
'northwind-labs': [{ number: 'NW-1001', total: '420.00 EUR' }],
'globex': [{ number: 'GX-2001', total: '99.00 EUR' }],
};
const app = express();
app.get('/customers/:slug/invoices', async (req, res) => {
let claims;
try {
const token = (req.headers.authorization ?? '').replace(/^Bearer /, '');
claims = await verifyAccessToken(token, { issuer, resource: audience });
} catch {
return res.status(401).json({ error: 'invalid_token' });
}
// LumoAuth sets the claims only for an active member of an active
// organization. A member of Northwind Labs never gets the slug of Globex.
if (claims.org_slug !== req.params.slug) {
return res.status(403).json({ error: 'not_your_organization' });
}
// An organization role is a name. Your code gives it a meaning.
if (!['owner', 'admin'].includes(claims.org_role)) {
return res.status(403).json({ error: 'role_not_allowed', role: claims.org_role });
}
res.json({ organization: claims.org_slug, role: claims.org_role, invoices: invoices[req.params.slug] ?? [] });
});
const port = Number(process.env.PORT ?? 3001);
app.listen(port, () => console.log(`The API listens on http://localhost:${port}`));
node b2b/customer-organizations/js/customer.mjs
#!/bin/sh
# Create a customer organization, make the person who signed up its owner,
# and invite a colleague as administrator, with the lumo CLI and jq.
#
# sh b2b/customer-organizations/cli/customer.sh
#
# The CLI has no command for customer organizations, so the script uses
# `lumo api`, which calls any path of the Admin API.
set -eu
SLUG="${CUSTOMER_SLUG:-northwind-labs}"
COLLEAGUE="${COLLEAGUE_EMAIL:-maya.chen@northwind.example.com}"
# The CLI reads its own three variables. With them it needs no `lumo login`.
export LUMO_BASE_URL="$LUMOAUTH_URL" LUMO_ORG="$LUMOAUTH_ORG_ID" LUMO_API_KEY="$LUMOAUTH_API_KEY"
# A second run answers 409, because the slug is taken. The next call reads the
# organization in both cases. The slug works in place of the ID in every path.
lumo api POST /organizations --data "{\"name\": \"Northwind Labs\", \"slug\": \"$SLUG\"}" > /dev/null 2>&1 || true
ID=$(lumo api GET "/organizations/$SLUG" | jq -r .data.id)
echo "organization: $SLUG ($ID)"
# Every customer organization starts with the roles owner, admin and member.
ROLES=$(lumo api GET "/organizations/$SLUG/roles")
OWNER_ROLE=$(printf '%s\n' "$ROLES" | jq '.data[] | select(.slug == "owner") | .id')
ADMIN_ROLE=$(printf '%s\n' "$ROLES" | jq '.data[] | select(.slug == "admin") | .id')
# The person who signed up has an account already, so no invitation is needed.
# A second run answers 409, because the person is a member.
lumo api POST "/organizations/$SLUG/members" \
--data "{\"userId\": \"$SIGNUP_USER_ID\", \"roleId\": $OWNER_ROLE}" > /dev/null 2>&1 || true
# The colleague gets an email with a link that works for 7 days. A second run
# sends no second email: LumoAuth limits how often one address is invited.
PENDING=$(lumo api GET "/organizations/$SLUG/invitations" --query status=pending | jq --arg email "$COLLEAGUE" '[.data[] | select(.email == $email)] | length')
if [ "$PENDING" = 0 ]; then
lumo api POST "/organizations/$SLUG/invitations" \
--data "{\"email\": \"$COLLEAGUE\", \"roleId\": $ADMIN_ROLE}" > /dev/null
fi
lumo api GET "/organizations/$SLUG/members" | jq -r '.data[] | "member: \(.user.email) as \(.role.slug)"'
lumo api GET "/organizations/$SLUG/invitations" --query status=pending | jq -r '.data[] | "invited: \(.email) as \(.role.slug)"'
echo "portal: $LUMOAUTH_URL/b2b/$LUMOAUTH_ORG_ID/$SLUG/"
sh b2b/customer-organizations/cli/customer.sh
Check the result
organization: northwind-labs (01a21fb8-7f58-72cf-b24f-d9a8fbc90258)
member: sam.rivera@northwind.example.com as owner
invited: maya.chen@northwind.example.com as admin
portal: https://app.lumoauth.dev/b2b/acme-corp/northwind-labs/
- In the portal, open Identity, Customer organizations, then Northwind Labs. The Members tab shows the owner, and the Pending invitations tab shows the colleague.
- Run a program again: the lines are the same, and no second email is sent.
To see the claims, sign in to your application as the owner. A member of one customer organization signs in through that one. A member of several chooses one on a selector. To skip the selector, your application adds the slug to the authorization request:
GET /orgs/acme-corp/api/v1/oauth/authorize?response_type=code&client_id=…&organization=northwind-labs&…
The access token then carries org_id, org_slug, org_name and org_role. Start js/api.mjs and call it with that token:
node b2b/customer-organizations/js/api.mjs
curl http://localhost:3001/customers/northwind-labs/invoices -H "Authorization: Bearer $ACCESS_TOKEN"
curl http://localhost:3001/customers/globex/invoices -H "Authorization: Bearer $ACCESS_TOKEN"
The first call answers with the invoices of Northwind Labs. The second call answers 403 with not_your_organization: a member of customer A cannot read the data of customer B.
To keep your own records in step, subscribe to the webhook events organization.created, organization.member.added and organization.invitation.accepted. See Receive webhooks.
Limits
- A customer organization has no SSO connection, SCIM endpoint or sign-in page of its own.
- An organization role is a name. LumoAuth attaches no permissions to it: your application gives each role its meaning.
- The
organizationparameter is a hint. LumoAuth ignores a slug of an organization in which the person is not an active member. - An opaque access token carries no claims. An application that uses opaque tokens reads the organization from the ID token.
- Tokens from the device flow and from CIBA carry no organization claims.
- LumoAuth limits how often one address is invited in an hour, so the programs send the invitation once.