Skip to main content

Sign-in for an Express app

Add login, callback and logout routes to an Express app, and protect the routes that need a session.

RecipeReadyView source
Works with
JavaScript / TypeScriptExpress

What it shows​

  1. lumoAuthMiddleware() adds the routes /auth/login, /auth/callback and /auth/logout to the app.
  2. /auth/login goes to the hosted sign-in page. The callback exchanges the code and keeps the tokens in the session on the server.
  3. The middleware sets req.user on every other request. A page that needs a person redirects to /auth/login when req.user is empty.
  4. requireAuth() protects an API route: it answers 401 without a session, and 403 when a scope is missing.
  5. /auth/logout clears the session and ends the session at LumoAuth. A small guard in front of it keeps other sites from signing the person out.

Before you start​

  • Node.js 20 or later.
  • An API key with the scopes admin:clients:read and admin:clients:write. Create it in the portal under Applications & developer tools, API keys.
  • A confidential application with the redirect URI http://localhost:3000/auth/callback. The setup script creates it.
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_KEYAn API key with the scopes admin:clients:read and admin:clients:write. Only the setup script uses it.
APP_URLOptional. The address of your app, when it is not http://localhost:3000. The setup script and the app read it.
LUMOAUTH_CLIENT_IDThe client ID of the application. The setup script prints it.
LUMOAUTH_CLIENT_SECRETThe client secret of the application. The setup script prints it.
SESSION_SECRETexpress-session signs its cookie with this value. The setup script prints a random value.

The setup script creates the application through the Admin API and prints the variables of the app. LumoAuth shows a client secret only once, so each run makes a new secret.

node sign-in/express/setup.mjs
setup.mjs
// Creates the application that the Express app signs in with: a confidential
// application with the callback address of the app. Run it again at any time.
//
// node sign-in/express/setup.mjs
//
// The API key needs the scopes admin:clients:read and admin:clients:write.
// APP_URL is the address of your app. The default is http://localhost:3000.
import { randomBytes } from 'node:crypto';
import { call, list, printEnv } from '../../_lib/admin.mjs';

const appUrl = (process.env.APP_URL ?? 'http://localhost:3000').replace(/\/+$/, '');
const name = 'Express sign-in';
const redirectUris = [`${appUrl}/auth/callback`];

let secret;
let client = (await list('/admin/clients')).find((c) => c.name === name);
if (client) {
// LumoAuth shows a client secret only once, so a second run makes a new one.
await call('PATCH', `/admin/clients/${client.id}`, { redirectUris });
secret = (await call('POST', `/admin/clients/${client.id}/rotate-secret`)).data.secret;
} else {
client = (await call('POST', '/admin/clients', { name, redirectUris, isConfidential: true })).data;
secret = client.secret;
}

console.log(`Application "${name}" is ready. Its redirect URI is ${redirectUris[0]}.`);
printEnv({
LUMOAUTH_CLIENT_ID: client.clientId,
LUMOAUTH_CLIENT_SECRET: secret,
// express-session signs its cookie with this value.
SESSION_SECRET: randomBytes(32).toString('hex'),
});

Copy the export lines that the script prints into the terminal where you start the app.

Sign-out returns to your app only when the address is registered. The Admin API has no field for it, so add it in the portal:

  1. Open Applications and select Express sign-in.
  2. Open the Configuration tab and go to the section Logout.
  3. Under Post-logout redirect URIs, enter http://localhost:3000/.
  4. Select Save configuration.

Code​

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. A browser signed in and out through the hosted page. A link and a form on another site did not sign the person out.

sign-in/express/js/server.mjs
// An Express app with sign-in: the hosted sign-in page, a session on the
// server, a protected page, a protected API route and sign-out.
//
// node sign-in/express/js/server.mjs
import express from 'express';
import session from 'express-session';
import { lumoAuthMiddleware, requireAuth } from '@lumoauth/express';

const appUrl = (process.env.APP_URL ?? 'http://localhost:3000').replace(/\/+$/, '');
const app = express();

// The session of express-session holds the tokens. The browser gets only the
// session cookie. Mount it before the LumoAuth middleware.
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: { httpOnly: true, sameSite: 'lax', secure: appUrl.startsWith('https:') },
}),
);

// 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 === new URL(appUrl).origin : 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>');
});

// Adds /auth/login, /auth/callback and /auth/logout, and sets req.user from
// the session on every other request.
app.use(
lumoAuthMiddleware({
baseUrl: process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev',
organization: process.env.LUMOAUTH_ORG_ID,
clientId: process.env.LUMOAUTH_CLIENT_ID,
clientSecret: process.env.LUMOAUTH_CLIENT_SECRET,
// An absolute address: sign-out then also ends the session at LumoAuth.
postLogoutRedirect: `${appUrl}/`,
}),
);

// A public page.
app.get('/', (req, res) => {
if (!req.user) return res.send('<p>Nobody is signed in.</p><a href="/auth/login">Sign in</a>');
res.send(
`<p>Signed in as ${req.user.email}.</p>` +
'<p><a href="/dashboard">Dashboard</a> · <a href="/api/me">Profile as JSON</a> · <a href="/auth/logout">Sign out</a></p>',
);
});

// A protected page: a signed-out visitor goes to sign-in and comes back here.
app.get('/dashboard', (req, res) => {
if (!req.user) return res.redirect('/auth/login?return_to=/dashboard');
res.send(`<h1>Dashboard</h1><p>User ID: ${req.user.sub}</p><a href="/">Home</a>`);
});

// A protected API route: requireAuth() answers 401 without a session.
app.get('/api/me', requireAuth(), (req, res) => {
res.json({ sub: req.user.sub, email: req.user.email, name: req.user.name });
});

// requireAuth() can also ask for scopes of the token: 403 when one is missing.
app.get('/api/email', requireAuth({ scopes: ['email'] }), (req, res) => {
res.json({ email: req.user.email });
});

app.listen(new URL(appUrl).port || 3000, () => console.log(`Listening on ${appUrl}`));
node sign-in/express/js/server.mjs

Check the result​

Open http://localhost:3000 in a browser, select Sign in, and sign in as a user of your organization.

Output
Signed out
GET / 200 Nobody is signed in.
GET /dashboard 302 /auth/login?return_to=/dashboard
GET /api/me 401 {"error":"unauthenticated"}

Signed in
GET / 200 Signed in as maya.chen@example.com.
GET /dashboard 200 User ID: 0195c1e2-7a41-7c3e-9b1d-2f6a8d4e5c10
GET /api/me 200 {"sub":"0195c1e2-7a41-7c3e-9b1d-2f6a8d4e5c10","email":"maya.chen@example.com","name":"Maya Chen"}
  • The browser holds only the cookie connect.sid of express-session, marked httpOnly. The tokens stay on the server.
  • Sign out returns to /, and the next visit to /dashboard shows the sign-in page again.
  • A link to /auth/logout on another site shows a page with the question "Do you want to sign out?". The person stays signed in until they select Sign out. A form on another site that posts to the route gets 403.

Limits​

  • requireAuth() answers with a status code. It does not redirect, so a page route sends the visitor to /auth/login itself.
  • The scopes option reads the scopes of the token in the session. It does not check roles or permissions: use the authorize option for that.
  • The default store of express-session keeps sessions in memory, so a restart signs everybody out. Use a shared store in production.
  • With a relative postLogoutRedirect, sign-out clears only the session of the app. The person stays signed in at LumoAuth.
  • Behind a reverse proxy, set trust proxy in Express. The middleware builds the callback address from the protocol and the host of the request.