Sign out of every application
End the session at LumoAuth, and tell the other applications of that session to sign the person out.
What it shows
- A person signs in to two applications of one organization: "Acme Store" and "Acme Help Center". The second sign-in asks for no password.
- 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. - LumoAuth ends its session, and sends a signed logout token to the back-channel logout address of each application.
- Each application verifies the token: the signature, the issuer, the audience and the logout event. Then it ends its sessions for the
sidof the token. - 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
localhostdoes 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.
| 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 the setup script only: an API key with the scope admin:clients:write. |
STORE_CLIENT_ID | The client ID of the application "Acme Store". The setup script prints it. |
HELP_CLIENT_ID | The 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:
- Open Applications, and open the application.
- Open the Configuration tab, and open the section Logout at the end of the form.
- In Post-logout redirect URIs, enter
http://localhost:3001/for "Acme Store", orhttp://localhost:3002/for "Acme Help Center". - In Back-channel logout URI, enter the public address of that application, followed by
/backchannel-logout. - 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.
- Node.js
- Python
// 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.
"""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.
python accounts/sign-out-everywhere/python/apps.py
"""
import asyncio
import os
import secrets
import time
from urllib.parse import urlencode
import jwt
import requests
import uvicorn
from fastapi import FastAPI, Form, Request
from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse, RedirectResponse, Response
from lumoauth.fastapi import lumo_auth_router
from starlette.middleware.sessions import SessionMiddleware
base_url = os.environ.get("LUMOAUTH_URL", "https://app.lumoauth.dev").rstrip("/")
organization = os.environ["LUMOAUTH_ORG_ID"]
# The discovery document names the issuer and the keys of the organization.
discovery = requests.get(f"{base_url}/orgs/{organization}/api/v1/.well-known/openid-configuration", timeout=10).json()
keys = jwt.PyJWKClient(discovery["jwks_uri"])
LOGOUT_EVENT = "http://schemas.openid.net/event/backchannel-logout"
def build(name: str, port: int, client_id: str) -> FastAPI:
app = FastAPI()
# The session of this application is a signed cookie, so the server cannot
# delete it. It keeps a list of the LumoAuth sessions that ended instead.
ended_sessions: set[str] = set()
ended_people: dict[str, float] = {}
# Each application has its own cookie name: both run on localhost.
app.add_middleware(SessionMiddleware, secret_key=secrets.token_hex(32), session_cookie=f"session-{port}")
# The router adds /auth/login, /auth/callback and /auth/logout. This
# application signs out with its own route /sign-out, below.
app.include_router(
lumo_auth_router(base_url=base_url, organization=organization, client_id=client_id),
prefix="/auth",
)
@app.middleware("http")
async def sign_out_guard(request: Request, call_next):
"""Another site must not be able to sign a person out. This guard covers
/sign-out and /auth/logout of the router. 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."""
if request.url.path not in ("/sign-out", "/auth/logout"):
return await call_next(request)
site, origin = request.headers.get("sec-fetch-site"), request.headers.get("origin")
if request.method == "POST":
if (origin == f"http://localhost:{port}") if origin not in (None, "null") else (site == "same-origin"):
return await call_next(request)
return PlainTextResponse("Sign-out refused: the request did not come from this app.", status_code=403)
if site in ("same-origin", "none"):
return await call_next(request)
return HTMLResponse(
'<p>Do you want to sign out?</p><form method="post"><button>Sign out</button></form>',
headers={
"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'",
},
)
def id_token_of(request: Request) -> str | None:
return (request.session.get("__lumoauth") or {}).get("tokens", {}).get("id_token")
def signed_in_user(request: Request) -> dict | None:
state = request.session.get("__lumoauth") or {}
id_token = id_token_of(request)
if not state.get("user") or not id_token:
return None
claims = jwt.decode(id_token, options={"verify_signature": False})
if claims.get("sid") in ended_sessions or claims["iat"] <= ended_people.get(claims["sub"], 0):
request.session.clear()
return None
return state["user"]
@app.post("/backchannel-logout")
def backchannel_logout(logout_token: str = Form("")) -> Response:
"""LumoAuth calls this address from its own servers, so the request has
no cookie. The signed logout token is the only proof."""
try:
header = jwt.get_unverified_header(logout_token)
# Verify it as you verify an ID token: signature, issuer and audience.
token = jwt.decode(
logout_token,
keys.get_signing_key_from_jwt(logout_token).key,
algorithms=["RS256", "ES256", "PS256"],
issuer=discovery["issuer"],
audience=client_id,
)
if header.get("typ") != "logout+jwt" or LOGOUT_EVENT not in token.get("events", {}) or "nonce" in token:
raise ValueError("not a logout token")
if not (token.get("sid") or token.get("sub")):
raise ValueError("no session and no person")
except Exception:
return JSONResponse({"error": "invalid_request"}, status_code=400)
# A token with no sid ends every session of the person.
if token.get("sid"):
ended_sessions.add(token["sid"])
else:
ended_people[token["sub"]] = time.time()
print(f"{name}: logout token accepted, session ended", flush=True)
return Response(status_code=200, headers={"Cache-Control": "no-store"})
@app.api_route("/sign-out", methods=["GET", "POST"])
def sign_out(request: Request) -> RedirectResponse:
"""End the session here, then at LumoAuth: redirect to the end-session
endpoint with the ID token as the hint. The button on the confirmation
page of sign_out_guard sends a POST."""
id_token = id_token_of(request)
request.session.clear()
query = {"post_logout_redirect_uri": f"http://localhost:{port}/"}
if id_token:
query["id_token_hint"] = id_token
return RedirectResponse(f"{discovery['end_session_endpoint']}?{urlencode(query)}", status_code=302)
@app.get("/", response_class=HTMLResponse)
def home(request: Request) -> str:
user = signed_in_user(request)
if user:
return f'<h1>{name}</h1><p>Signed in as {user["email"]}.</p><p><a href="/sign-out">Sign out</a></p>'
return f'<h1>{name}</h1><p>Signed out.</p><p><a href="/auth/login">Sign in</a></p>'
print(f"{name}: http://localhost:{port}", flush=True)
return app
async def main() -> None:
apps = [
("Acme Store", int(os.environ.get("STORE_PORT", 3001)), os.environ["STORE_CLIENT_ID"]),
("Acme Help Center", int(os.environ.get("HELP_PORT", 3002)), os.environ["HELP_CLIENT_ID"]),
]
servers = [
uvicorn.Server(uvicorn.Config(build(name, port, client_id), port=port, log_level="warning"))
for name, port, client_id in apps
]
await asyncio.gather(*(server.serve() for server in servers))
asyncio.run(main())
python accounts/sign-out-everywhere/python/apps.py
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
- Open
http://localhost:3001and sign in. Openhttp://localhost:3002and click Sign in: LumoAuth asks for no password. - Click Sign out in the store. The browser returns to the store, which shows "Signed out".
- Reload the help center. It shows "Signed out" too.
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/logoutin Node.js and/sign-outin 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.