MFA and step-up for one action
Require a second factor for the organization, and ask for a fresh one before a sensitive action.
What it shows
- 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, andauth_time, the time of the sign-in. - A token from a sign-in with a password only, or from an old sign-in, gets
401with a step-up challenge. TheWWW-Authenticateheader saysinsufficient_user_authenticationand names theacr_valuesand themax_agethat the API needs. - The web app reads the challenge and sends the person to LumoAuth again, with the same
acr_valuesandmax_age. - LumoAuth asks for the second factor. A person who has none sets one up first, on the page Secure your account.
- 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.
| 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 scopes admin:clients:read, admin:clients:write and admin:settings:read. |
APP_URL | Optional. The address of the web app, when it is not http://localhost:3000. The setup script and the app read it. |
LUMOAUTH_CLIENT_ID | The client ID of the application. The setup script prints it. |
LUMOAUTH_CLIENT_SECRET | The client secret of the application. The setup script prints it. |
SESSION_SECRET | The session cookie of the app is signed with this value. The setup script prints a random value. |
API_URL | Optional. The address of the Payouts API. The default is http://localhost:4001. |
API_RESOURCE | Optional. The identifier of the Payouts API, which its tokens carry as the audience. The default is https://payouts.example.com. |
MAX_AGE | Optional. 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.
- Express
- FastAPI
// 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 });
});
// 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.
"""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 os
import time
from fastapi import Depends, FastAPI
from fastapi.responses import JSONResponse
from lumoauth import LumoAuth
from lumoauth.fastapi import AccessTokenClaims, require_access_token
# The identifier of this API. Tokens name it as their audience.
API_RESOURCE = os.environ.get("API_RESOURCE", "https://payouts.example.com")
# A payout needs a second factor that is at most this old, in seconds.
MAX_AGE = int(os.environ.get("MAX_AGE", "300"))
# An authenticator app (tier 3) or a stronger factor.
STRONG_ENOUGH = {"urn:lumoauth:acr:mfa", "urn:lumoauth:acr:mfa:strong", "urn:lumoauth:acr:mfa:phr"}
# Verifies the signature, the issuer, the expiry and the audience of the token.
token = require_access_token(issuer=LumoAuth().issuer, resource=API_RESOURCE)
api = FastAPI()
@api.get("/balance")
def balance(claims: AccessTokenClaims = Depends(token)):
"""Any signed-in person may read the balance."""
return {"balance": "1,250.00 EUR", "amr": claims.claims.get("amr", [])}
@api.post("/payouts")
def payouts(claims: AccessTokenClaims = Depends(token)):
"""acr names the strongest factor of the sign-in. auth_time is when the person signed in."""
acr = claims.claims.get("acr")
auth_time = claims.claims.get("auth_time")
recent = isinstance(auth_time, int) and time.time() - auth_time <= MAX_AGE
if acr not in STRONG_ENOUGH or not recent:
# The challenge tells the app what to ask LumoAuth for.
challenge = (
'Bearer error="insufficient_user_authentication", '
'error_description="A recent second factor is required", '
f'acr_values="urn:lumoauth:acr:mfa", max_age="{MAX_AGE}"'
)
return JSONResponse({"error": "insufficient_user_authentication"}, status_code=401, headers={"WWW-Authenticate": challenge})
return JSONResponse({"payout": "sent", "amount": "250.00 EUR", "acr": acr, "amr": claims.claims.get("amr", [])}, status_code=201)
"""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.
python sign-in/mfa-and-step-up/python/app.py
Then open http://localhost:3000.
"""
import asyncio
import base64
import hashlib
import os
import re
import secrets
from urllib.parse import urlparse
import requests
import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from lumoauth import LumoAuth
from starlette.middleware.sessions import SessionMiddleware
from api import API_RESOURCE, api
APP_URL = os.environ.get("APP_URL", "http://localhost:3000").rstrip("/")
API_URL = os.environ.get("API_URL", "http://localhost:4001").rstrip("/")
REDIRECT_URI = f"{APP_URL}/callback"
CLIENT_ID = os.environ["LUMOAUTH_CLIENT_ID"]
lumo = LumoAuth()
app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key=os.environ["SESSION_SECRET"], same_site="lax", https_only=APP_URL.startswith("https:"))
def start_sign_in(request: Request, step_up: dict | None = None):
"""Sends the browser to LumoAuth. A step-up adds acr_values and max_age."""
verifier = secrets.token_urlsafe(48)
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
state = secrets.token_urlsafe(24)
url = lumo.auth.authorization_url(
client_id=CLIENT_ID,
redirect_uri=REDIRECT_URI,
state=state,
code_challenge=challenge,
extra={"resource": API_RESOURCE, **(step_up or {})},
)
# After a step-up, the callback repeats the payout.
request.session["flow"] = {"verifier": verifier, "state": state, "repeat_payout": bool(step_up)}
return RedirectResponse(url, status_code=303)
def call_api(request: Request, method: str, path: str):
return requests.request(method, API_URL + path, headers={"Authorization": f"Bearer {request.session['access_token']}"}, timeout=10)
def parse_challenge(header: str | None) -> dict:
"""Reads the parameters of a challenge, for example acr_values="urn:lumoauth:acr:mfa"."""
return dict(re.findall(r'(\w+)="([^"]*)"', header or ""))
def send_payout(request: Request, after_step_up: bool = False):
answer = call_api(request, "POST", "/payouts")
challenge = parse_challenge(answer.headers.get("www-authenticate"))
if answer.status_code == 401 and challenge.get("error") == "insufficient_user_authentication":
print(f'POST /payouts -> 401 {challenge["error"]}, acr_values="{challenge.get("acr_values")}", max_age="{challenge.get("max_age")}"', flush=True)
# Ask once. A refusal right after the step-up is shown, not repeated.
if not after_step_up:
return start_sign_in(request, {k: challenge[k] for k in ("acr_values", "max_age") if k in challenge})
if not answer.ok:
return HTMLResponse(f'<p>The payout was refused ({answer.status_code}).</p><a href="/">Back</a>', status_code=answer.status_code)
body = answer.json()
print(f"POST /payouts -> {answer.status_code} {body['payout']}, signed in with: {' '.join(body['amr'])} ({body['acr']})", flush=True)
return HTMLResponse(f'<p>Payout sent: {body["amount"]}.</p><a href="/">Back</a>')
@app.get("/login")
def login(request: Request):
return start_sign_in(request)
@app.get("/callback")
def callback(request: Request, code: str = "", state: str = ""):
flow = request.session.pop("flow", None)
if not flow or state != flow["state"]:
return HTMLResponse("No sign-in in progress.", status_code=400)
tokens = lumo.auth.exchange_code(
code,
REDIRECT_URI,
client_id=CLIENT_ID,
client_secret=os.environ.get("LUMOAUTH_CLIENT_SECRET"),
code_verifier=flow["verifier"],
)
request.session["access_token"] = tokens["access_token"]
if flow["repeat_payout"]:
return send_payout(request, after_step_up=True)
return RedirectResponse("/", status_code=303)
@app.get("/")
def home(request: Request):
if "access_token" not in request.session:
return HTMLResponse('<p>Nobody is signed in.</p><a href="/login">Sign in</a>')
answer = call_api(request, "GET", "/balance")
if not answer.ok:
return HTMLResponse('<p>The session has ended.</p><a href="/login">Sign in</a>')
body = answer.json()
print(f"GET /balance -> {answer.status_code}, signed in with: {' '.join(body['amr'])}", flush=True)
return HTMLResponse(
f"<p>Balance: {body['balance']}</p>"
'<form method="post" action="/payouts"><button>Send 250.00 EUR</button></form>'
)
@app.post("/payouts")
def payouts(request: Request):
return send_payout(request)
async def main():
# The API and the app run side by side, each on its own port.
servers = [
uvicorn.Server(uvicorn.Config(api, port=urlparse(API_URL).port or 4001, log_level="warning")),
uvicorn.Server(uvicorn.Config(app, port=urlparse(APP_URL).port or 3000, log_level="warning")),
]
print(f"Listening on {APP_URL}", flush=True)
await asyncio.gather(*(server.serve() for server in servers))
if __name__ == "__main__":
asyncio.run(main())
python sign-in/mfa-and-step-up/python/app.py
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:
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_agemakes LumoAuth ask for the password, then the second factor. Start the app withMAX_AGE=30to see it sooner. lumo mfa coveragecounts the people who have set up a second factor.
Limits
- The app has its own sign-in routes. The routes of
@lumoauth/expressandlumo_auth_routerof the Python SDK do not passacr_valuesormax_ageto LumoAuth. acris 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_valuesasks for a level. Always check theacrclaim of the token that comes back, as the API does.