Skip to main content

Sign out of every application

End the session at LumoAuth, and tell the other applications of that session to sign the person out.

RecipeDraftView source
This page is a draft. The code exists, and not all of it has been run for this page yet. The page says what was checked.
Works with
JavaScript / TypeScriptPythonExpressFastAPI

What it shows​

  1. A person signs in to two applications of one organization: "Acme Store" and "Acme Help Center". The second sign-in asks for no password.
  2. The person signs out in one application. That application ends its own session, and redirects the browser to the end-session endpoint with the ID token as id_token_hint.
  3. LumoAuth ends its session, and sends a signed logout token to the back-channel logout address of each application.
  4. Each application verifies the token: the signature, the issuer, the audience and the logout event. Then it ends its sessions for the sid of the token.
  5. LumoAuth redirects the browser to the post-logout address of the first application.

The program starts both applications in one process, so that you see the two sides together.

Before you start​

  • Two applications in one organization. The setup script creates them. Its API key needs the scope admin:clients:write.
  • A public HTTPS address for each application. LumoAuth calls the back-channel logout address from its own servers, so localhost does not work there. On your own machine, use a tunnel that forwards a public HTTPS address to port 3001, and a second one to port 3002.
VariableValue
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
LUMOAUTH_API_KEYFor the setup script only: an API key with the scope admin:clients:write.
STORE_CLIENT_IDThe client ID of the application "Acme Store". The setup script prints it.
HELP_CLIENT_IDThe client ID of the application "Acme Help Center".

The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.

node accounts/sign-out-everywhere/setup.mjs
setup.mjs
// Creates the two applications of the recipe: "Acme Store" on port 3001 and
// "Acme Help Center" on port 3002. Run it again at any time.
//
// node accounts/sign-out-everywhere/setup.mjs
//
// The API key needs the scope admin:clients:write. The logout addresses of an
// application are set in the portal: the page of the recipe has the steps.
import { call, ensure, printEnv } from '../../_lib/admin.mjs';

const application = async (name, port) => {
const redirectUris = [`http://localhost:${port}/auth/callback`];
const found = await ensure('/admin/clients', (c) => c.name === name, {
name,
redirectUris,
// A public application signs in with PKCE and has no secret to keep.
isConfidential: false,
});
// A second run with another port replaces the redirect address.
await call('PATCH', `/admin/clients/${found.clientId}`, { redirectUris });
return found;
};

const store = await application('Acme Store', process.env.STORE_PORT ?? 3001);
const help = await application('Acme Help Center', process.env.HELP_PORT ?? 3002);

console.log('The applications "Acme Store" and "Acme Help Center" are ready.');
printEnv({ STORE_CLIENT_ID: store.clientId, HELP_CLIENT_ID: help.clientId });

The logout addresses of an application are set in the portal. Do this for each of the two applications:

  1. Open Applications, and open the application.
  2. Open the Configuration tab, and open the section Logout at the end of the form.
  3. In Post-logout redirect URIs, enter http://localhost:3001/ for "Acme Store", or http://localhost:3002/ for "Acme Help Center".
  4. In Back-channel logout URI, enter the public address of that application, followed by /backchannel-logout.
  5. Click Save configuration.

Code​

Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Both programs signed a person in to the two applications and ended the session at LumoAuth. A link and a form on another site did not sign the person out. The route for the logout token refused a wrong token, and it was not called by LumoAuth in the test.

accounts/sign-out-everywhere/js/apps.mjs
// Two applications of one organization, in one process: "Acme Store" and
// "Acme Help Center". Sign in to both, then sign out in one of them. LumoAuth
// ends its session and sends a logout token to the other application.
//
// node accounts/sign-out-everywhere/js/apps.mjs
import express from 'express';
import session from 'express-session';
import { createRemoteJWKSet, decodeJwt, jwtVerify } from 'jose';
import { randomBytes } from 'node:crypto';
import { lumoAuthMiddleware } from '@lumoauth/express';

const baseUrl = (process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev').replace(/\/+$/, '');
const organization = process.env.LUMOAUTH_ORG_ID;

// The discovery document names the issuer and the keys of the organization.
const discovery = await (await fetch(`${baseUrl}/orgs/${organization}/api/v1/.well-known/openid-configuration`)).json();
const keys = createRemoteJWKSet(new URL(discovery.jwks_uri));
const LOGOUT_EVENT = 'http://schemas.openid.net/event/backchannel-logout';

function start(name, port, clientId) {
const store = new session.MemoryStore();
const app = express();

// Back-channel logout. LumoAuth calls this address from its own servers, so
// the request has no cookie. The signed logout token is the only proof.
app.post('/backchannel-logout', express.urlencoded({ extended: false }), async (req, res) => {
let token;
try {
// Verify it as you verify an ID token: signature, issuer and audience.
({ payload: token } = await jwtVerify(req.body?.logout_token ?? '', keys, {
issuer: discovery.issuer,
audience: clientId,
typ: 'logout+jwt',
}));
if (!token.events?.[LOGOUT_EVENT] || token.nonce || !(token.sid || token.sub)) throw new Error('not a logout token');
} catch {
res.status(400).json({ error: 'invalid_request' });
return;
}
// End each of this application's sessions that belongs to the LumoAuth
// session. A token with no sid ends every session of the person.
store.all((error, sessions) => {
for (const [id, data] of Object.entries(sessions ?? {})) {
const idToken = data.__lumoAuth?.tokens?.id_token;
const claims = idToken ? decodeJwt(idToken) : {};
if (token.sid ? claims.sid === token.sid : claims.sub === token.sub) store.destroy(id);
}
console.log(`${name}: logout token accepted, session ended`);
res.set('Cache-Control', 'no-store').sendStatus(200);
});
});

// Each application has its own cookie name: both run on localhost.
app.use(session({ name: `session-${port}`, store, secret: randomBytes(32).toString('hex'), resave: false, saveUninitialized: false }));

// Another site must not be able to sign a person out. This guard runs before
// /auth/logout of the middleware. A GET signs out at once only when the
// browser says that it comes from this app or from a typed address. Any
// other GET gets a page with a button, and a POST must come from this app.
app.all('/auth/logout', (req, res, next) => {
const site = req.get('Sec-Fetch-Site');
if (req.method === 'POST') {
const origin = req.get('Origin');
if (origin && origin !== 'null' ? origin === `http://localhost:${port}` : site === 'same-origin') return next();
return res.status(403).send('Sign-out refused: the request did not come from this app.');
}
if (site === 'same-origin' || site === 'none') return next();
res.set({
'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Referrer-Policy': 'same-origin',
// No form-action: Chromium applies it to the redirect to LumoAuth too.
'Content-Security-Policy': "default-src 'none'; frame-ancestors 'none'",
});
res.send('<p>Do you want to sign out?</p><form method="post"><button>Sign out</button></form>');
});

// The middleware adds /auth/login, /auth/callback and /auth/logout. With an
// absolute return address, /auth/logout also ends the session at LumoAuth:
// it redirects to the end-session endpoint with the ID token as the hint.
app.use(lumoAuthMiddleware({ baseUrl, organization, clientId, postLogoutRedirect: `http://localhost:${port}/` }));

app.get('/', (req, res) => {
res.send(
req.user
? `<h1>${name}</h1><p>Signed in as ${req.user.email}.</p><p><a href="/auth/logout">Sign out</a></p>`
: `<h1>${name}</h1><p>Signed out.</p><p><a href="/auth/login">Sign in</a></p>`,
);
});

app.listen(port, () => console.log(`${name}: http://localhost:${port}`));
}

start('Acme Store', process.env.STORE_PORT ?? 3001, process.env.STORE_CLIENT_ID);
start('Acme Help Center', process.env.HELP_PORT ?? 3002, process.env.HELP_CLIENT_ID);
node accounts/sign-out-everywhere/js/apps.mjs

Compiles. Not run against an organization. Sign-in and the sign-out at LumoAuth ran against an organization. No logout token arrived: LumoAuth sends it only to a public HTTPS address, and the test had none.

Check the result​

  1. Open http://localhost:3001 and sign in. Open http://localhost:3002 and click Sign in: LumoAuth asks for no password.
  2. Click Sign out in the store. The browser returns to the store, which shows "Signed out".
  3. Reload the help center. It shows "Signed out" too.
Output
Acme Store: http://localhost:3001
Acme Help Center: http://localhost:3002
Acme Store: logout token accepted, session ended
Acme Help Center: logout token accepted, session ended
  • Without step 4 of the portal steps, the help center stays signed in until its own session ends. The session at LumoAuth is ended in both cases: a new sign-in asks for the password.
  • A sign-out on a LumoAuth page, a session that an administrator revokes, and a blocked account send the same logout token.
  • A link to the sign-out route on another site shows a page with the question "Do you want to sign out?". A form on another site that posts to the route gets 403. The route is /auth/logout in Node.js and /sign-out in Python.

Limits​

  • LumoAuth sends logout tokens only over HTTPS, and only to an address that is reachable from the internet.
  • The tokens are sent from a queue. An application can receive its token a short time after the browser has returned.
  • An application that received no token keeps its own session. Give your own session a lifetime for that case.
  • A browser-only app has no server for the back-channel call. The logout page of the docs describes front-channel logout for that case.
  • The applications of the recipe keep their sessions in memory. With several servers, keep the sessions, or the list of ended sessions, in a shared store.