Skip to main content

MFA and step-up for one action

Require a second factor for the organization, and ask for a fresh one before a sensitive action.

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
Standards
RFC 9470

What it shows​

  1. The Payouts API verifies the access token of each request. Before a payout, it reads two claims: acr, the strongest factor of the sign-in, and auth_time, the time of the sign-in.
  2. A token from a sign-in with a password only, or from an old sign-in, gets 401 with a step-up challenge. The WWW-Authenticate header says insufficient_user_authentication and names the acr_values and the max_age that the API needs.
  3. The web app reads the challenge and sends the person to LumoAuth again, with the same acr_values and max_age.
  4. LumoAuth asks for the second factor. A person who has none sets one up first, on the page Secure your account.
  5. The app gets a new token and sends the payout again. The API accepts it.

The API decides what it needs. The app does not hold the rule: it passes on what the challenge asks for.

Before you start​

  • The MFA policy of the organization. The setup script prints it. Under Risk-based, the default, a person without a second factor is not asked for one at sign-in: the step-up asks when the API needs it.
  • To require a second factor from everybody at sign-in, open Sign-in settings in the portal, choose MFA policy, and set Requirement to Required.
  • A user with a password, and an authenticator app on a phone, such as Google Authenticator or 1Password.
  • The application "Payouts dashboard", a confidential web app. 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_KEYFor the setup script only: an API key with the scopes admin:clients:read, admin:clients:write and admin:settings:read.
APP_URLOptional. The address of the web 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_SECRETThe session cookie of the app is signed with this value. The setup script prints a random value.
API_URLOptional. The address of the Payouts API. The default is http://localhost:4001.
API_RESOURCEOptional. The identifier of the Payouts API, which its tokens carry as the audience. The default is https://payouts.example.com.
MAX_AGEOptional. How old the sign-in may be for a payout, in seconds. The default is 300.

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

node sign-in/mfa-and-step-up/setup.mjs
setup.mjs
// Creates the application that the payouts app signs in with: a confidential
// application with the callback address of the app. It also prints the MFA
// policy of the organization. Run it again at any time.
//
// node sign-in/mfa-and-step-up/setup.mjs
//
// The API key needs admin:clients:read, admin:clients:write and admin:settings:read.
// 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 = 'Payouts dashboard';
const redirectUris = [`${appUrl}/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]}.`);

// The policy says who must use a second factor and which factors count.
const policy = (await call('GET', '/admin/policies/mfa')).data;
console.log(`MFA policy: requirement ${policy.requirement}, factors ${policy.allowed_factors.join(', ')}`);

printEnv({
LUMOAUTH_CLIENT_ID: client.clientId,
LUMOAUTH_CLIENT_SECRET: secret,
// express-session and Starlette sign their cookie with this value.
SESSION_SECRET: randomBytes(32).toString('hex'),
});

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. In each language the first file is the API and the second file is the web app, which also starts the API. A browser signed in with a password, set up an authenticator app at the step-up, and came back with the payout sent. The step-up of a person who already had an authenticator app was checked only in part.

sign-in/mfa-and-step-up/js/api.mjs
// The Payouts API. It verifies the access token of each request. Before it
// sends money, it checks how and when the person signed in. When that is not
// enough, it answers with a step-up challenge (RFC 9470).
import express from 'express';
import { AccessTokenError, createAccessTokenVerifier, issuerFor } from '@lumoauth/agent';

// The identifier of this API. Tokens name it as their audience.
export const API_RESOURCE = process.env.API_RESOURCE ?? 'https://payouts.example.com';
// A payout needs a second factor that is at most this old, in seconds.
const MAX_AGE = Number(process.env.MAX_AGE ?? 300);
// An authenticator app (tier 3) or a stronger factor.
const STRONG_ENOUGH = ['urn:lumoauth:acr:mfa', 'urn:lumoauth:acr:mfa:strong', 'urn:lumoauth:acr:mfa:phr'];

const verifier = createAccessTokenVerifier({
issuer: issuerFor(process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev', process.env.LUMOAUTH_ORG_ID),
resource: API_RESOURCE,
});

export const api = express();

api.use(async (req, res, next) => {
try {
const url = `${req.protocol}://${req.get('host')}${req.originalUrl}`;
req.token = await verifier.verifyRequest({ method: req.method, url, headers: req.headers });
next();
} catch (error) {
if (!(error instanceof AccessTokenError)) return next(error);
res.status(401).set('WWW-Authenticate', 'Bearer error="invalid_token"').json({ error: 'invalid_token' });
}
});

// Any signed-in person may read the balance.
api.get('/balance', (req, res) => {
res.json({ balance: '1,250.00 EUR', amr: req.token.amr ?? [] });
});

// acr names the strongest factor of the sign-in. auth_time is when the person signed in.
api.post('/payouts', (req, res) => {
const { acr, amr, auth_time: authTime } = req.token;
const recent = typeof authTime === 'number' && Date.now() / 1000 - authTime <= MAX_AGE;
if (!STRONG_ENOUGH.includes(acr) || !recent) {
// The challenge tells the app what to ask LumoAuth for.
res.set(
'WWW-Authenticate',
`Bearer error="insufficient_user_authentication", error_description="A recent second factor is required", acr_values="urn:lumoauth:acr:mfa", max_age="${MAX_AGE}"`,
);
return res.status(401).json({ error: 'insufficient_user_authentication' });
}
res.status(201).json({ payout: 'sent', amount: '250.00 EUR', acr, amr });
});
sign-in/mfa-and-step-up/js/app.mjs
// A web app that calls the Payouts API for a signed-in person. When the API
// asks for a stronger or a more recent sign-in, the app sends the person to
// LumoAuth again with the values of the challenge, then repeats the call.
//
// node sign-in/mfa-and-step-up/js/app.mjs
//
// Then open http://localhost:3000.
import express from 'express';
import session from 'express-session';
import { AuthModule } from '@lumoauth/client';
import { api, API_RESOURCE } from './api.mjs';

const appUrl = (process.env.APP_URL ?? 'http://localhost:3000').replace(/\/+$/, '');
const apiUrl = (process.env.API_URL ?? 'http://localhost:4001').replace(/\/+$/, '');
const redirectUri = `${appUrl}/callback`;

const auth = new AuthModule({
baseUrl: process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev',
orgId: process.env.LUMOAUTH_ORG_ID,
clientId: process.env.LUMOAUTH_CLIENT_ID,
});

const app = express();
app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false, cookie: { httpOnly: true, sameSite: 'lax' } }));

// Sends the browser to LumoAuth. A step-up adds acr_values and max_age.
async function startSignIn(req, res, stepUp = {}) {
const extraParams = { resource: API_RESOURCE, ...stepUp };
const { url, codeVerifier, state } = await auth.buildAuthorizationUrl({ redirectUri, extraParams });
// After a step-up, the callback repeats the payout.
req.session.flow = { codeVerifier, state, repeatPayout: Object.keys(stepUp).length > 0 };
res.redirect(303, url);
}

function callApi(req, method, path) {
return fetch(apiUrl + path, { method, headers: { Authorization: `Bearer ${req.session.accessToken}` } });
}

// Reads the parameters of a challenge, for example acr_values="urn:lumoauth:acr:mfa".
function parseChallenge(header) {
return Object.fromEntries([...(header ?? '').matchAll(/(\w+)="([^"]*)"/g)].map((match) => [match[1], match[2]]));
}

async function sendPayout(req, res, afterStepUp = false) {
const answer = await callApi(req, 'POST', '/payouts');
const challenge = parseChallenge(answer.headers.get('www-authenticate'));
if (answer.status === 401 && challenge.error === 'insufficient_user_authentication') {
console.log(`POST /payouts -> 401 ${challenge.error}, acr_values="${challenge.acr_values}", max_age="${challenge.max_age}"`);
// Ask once. A refusal right after the step-up is shown, not repeated.
if (!afterStepUp) {
const stepUp = Object.fromEntries(['acr_values', 'max_age'].filter((name) => challenge[name]).map((name) => [name, challenge[name]]));
return startSignIn(req, res, stepUp);
}
}
if (!answer.ok) return res.status(answer.status).send(`<p>The payout was refused (${answer.status}).</p><a href="/">Back</a>`);
const body = await answer.json();
console.log(`POST /payouts -> ${answer.status} ${body.payout}, signed in with: ${body.amr.join(' ')} (${body.acr})`);
res.send(`<p>Payout sent: ${body.amount}.</p><a href="/">Back</a>`);
}

app.get('/login', (req, res) => startSignIn(req, res));

app.get('/callback', async (req, res) => {
const flow = req.session.flow;
if (!flow || req.query.state !== flow.state) return res.status(400).send('No sign-in in progress.');
const tokens = await auth.exchangeCodeForTokens({
code: req.query.code,
codeVerifier: flow.codeVerifier,
redirectUri,
clientSecret: process.env.LUMOAUTH_CLIENT_SECRET,
});
// A new session ID after each sign-in, so that an ID from before is worth nothing.
await new Promise((resolve, reject) => req.session.regenerate((error) => (error ? reject(error) : resolve())));
req.session.accessToken = tokens.access_token;
if (flow.repeatPayout) return sendPayout(req, res, true);
res.redirect('/');
});

app.get('/', async (req, res) => {
if (!req.session.accessToken) return res.send('<p>Nobody is signed in.</p><a href="/login">Sign in</a>');
const answer = await callApi(req, 'GET', '/balance');
if (!answer.ok) return res.send('<p>The session has ended.</p><a href="/login">Sign in</a>');
const body = await answer.json();
console.log(`GET /balance -> ${answer.status}, signed in with: ${body.amr.join(' ')}`);
res.send(
`<p>Balance: ${body.balance}</p>` +
'<form method="post" action="/payouts"><button>Send 250.00 EUR</button></form>',
);
});

app.post('/payouts', (req, res) => sendPayout(req, res));

api.listen(new URL(apiUrl).port || 4001);
app.listen(new URL(appUrl).port || 3000, () => console.log(`Listening on ${appUrl}`));
node sign-in/mfa-and-step-up/js/app.mjs

Open http://localhost:3000.

Check the result​

Open http://localhost:3000, click Sign in and sign in with the password. The app shows the balance. Click Send 250.00 EUR. LumoAuth asks for the second factor, or asks the person to set up an authenticator app first. The browser then comes back, and the payout is sent. The app prints:

Output
Listening on http://localhost:3000
GET /balance -> 200, signed in with: pwd
POST /payouts -> 401 insufficient_user_authentication, acr_values="urn:lumoauth:acr:mfa", max_age="300"
POST /payouts -> 201 sent, signed in with: pwd otp mfa (urn:lumoauth:acr:mfa)
  • Click Send 250.00 EUR again. The API accepts the new token at once.
  • Five minutes after the sign-in, the next payout asks again. max_age makes LumoAuth ask for the password, then the second factor. Start the app with MAX_AGE=30 to see it sooner.
  • lumo mfa coverage counts the people who have set up a second factor.

Limits​

  • The app has its own sign-in routes. The routes of @lumoauth/express and lumo_auth_router of the Python SDK do not pass acr_values or max_age to LumoAuth.
  • acr is missing when the second factor was skipped, for example on a trusted device. The API then asks for the step-up, as for a sign-in with a password only.
  • The API accepts only tokens that were issued for it: the app asks for them with resource. See Verify access tokens in your API.
  • acr_values asks for a level. Always check the acr claim of the token that comes back, as the API does.