Skip to main content

Protect routes in each framework

Refuse a request before the handler runs, with the idiom of each framework: middleware, a dependency, an attribute or an annotation.

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 / TypeScriptPythonGoJavaC# / .NETPHPPlain HTTPExpressNext.jsFastAPIGo net/httpSpring BootASP.NET CoreLaravelSymfony

What it shows​

  1. The same API in eight frameworks, with three routes: GET /public for everybody, GET /me for a valid access token, and PUT /documents/{id}, which needs documents.edit.
  2. The helper of the framework checks the bearer token before the handler runs. A missing or refused token gets 401.
  3. The permission check runs next. A person without the permission gets 403.
  4. try.sh calls the three routes without a token, as a reader and as an editor.

The versions check a token in one of three ways. The kind of token that a version takes depends on its way:

  • Express, FastAPI and Go check the token themselves, with the key set of your organization. The token must name the API in aud: your client asks for it with the parameter resource=http://localhost:3001. The API key then asks LumoAuth whether the person that the token names holds the permission.
  • Laravel and Symfony ask LumoAuth about each token. The API key then asks about the person that the token names. They take both kinds of token.
  • Next.js, Spring Boot and ASP.NET Core ask LumoAuth about each token, and check the permission with the token of the caller. They take the access token that your application receives at sign-in, without resource.

Three versions add a few lines where their package has no helper:

  • Laravel adds a guard that asks LumoAuth about the token. The middleware lumoauth.permission of lumoauth/laravel then checks the permission.
  • Symfony adds a voter for #[IsGranted] and a user provider. The token handler of lumoauth/symfony-bundle checks the token.
  • Next.js adds two wrappers for route handlers, with the client of @lumoauth/client. The root of @lumoauth/nextjs is for client components, so a route handler cannot create its client.

Before you start​

  • An API key with the scope authz:check. Create it in the portal under Applications & developer tools, API keys.
  • The permission documents.edit, a role that holds it, and a user who holds the role. The setup script creates the permission and the role, and gives the role to the user that EDITOR_EMAIL names.
  • A second user without the role, the reader.
  • An access token for each of the two users, from an application of your organization. See above for the kind of token that each version needs.
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 scope authz:check. Express, FastAPI, Go, Laravel and Symfony use it to ask about the person that a token names. The setup script also needs admin:permissions:write, admin:roles:write, admin:users:read and admin:users:write.
EDITOR_EMAILFor the setup script: the email address of the user who tests as the editor.
API_AUDIENCEOptional, for Express, FastAPI and Go. The address that a token must name in aud. The default is http://localhost:3001.
PORTOptional. The port of the API. The default is 3001. Next.js, Laravel and Symfony take the port in their command instead.
PERMISSIONOptional, for Express, FastAPI, Go, Next.js and ASP.NET Core. The permission of the edit route. The default is documents.edit. Spring Boot, Laravel and Symfony name it in the code instead.
READER_TOKENFor try.sh: an access token of a user who does not hold the permission.
EDITOR_TOKENFor try.sh: an access token of the editor.
API_URLOptional, for try.sh. The address of the running API. The default is http://localhost:3001.

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

EDITOR_EMAIL=erin@example.com node authorization/protect-routes/setup.mjs
setup.mjs
// Creates what the recipe needs: the permission documents.edit, a role that
// holds it, and gives the role to the person who tests as the editor. Run it
// again at any time.
//
// EDITOR_EMAIL=erin@example.com node authorization/protect-routes/setup.mjs
//
// The API key needs the scopes admin:permissions:write, admin:roles:write,
// admin:users:read and admin:users:write.
import { call, ensure, list } from '../../_lib/admin.mjs';

const email = process.env.EDITOR_EMAIL;
if (!email) {
console.error('Set EDITOR_EMAIL to the email address of an existing user.');
process.exit(1);
}

const permission = await ensure('/admin/permissions', (p) => p.slug === 'documents.edit', {
name: 'Edit documents',
slug: 'documents.edit',
description: 'Change the text of a document.',
});

const role = await ensure('/admin/roles', (r) => r.slug === 'content-editor', {
name: 'Content editor',
slug: 'content-editor',
description: 'May edit documents.',
});
await call('PUT', `/admin/roles/${role.id}/permissions`, { permissions: [permission.slug] });

const editor = (await list(`/admin/users?search=${encodeURIComponent(email)}`)).find((u) => u.email === email);
if (!editor) {
console.error(`No user has the email address ${email}.`);
process.exit(1);
}
const roles = (await call('GET', `/admin/users/${editor.id}/roles`)).data ?? [];
if (!roles.some((r) => r.slug === role.slug)) {
await call('POST', `/admin/users/${editor.id}/roles`, { roleSlug: role.slug });
}

console.log(`${email} holds the role ${role.slug}, which holds ${permission.slug}.`);

Code​

Start one version of the API, then run try.sh in a second terminal.

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. Each API was run, and try.sh printed these lines against it. The Next.js version was run with next build and next start. On a new organization the setup script stops at the step that adds the new permission to the role.

authorization/protect-routes/js/express.mjs
// An API in Express with three routes: one for everybody, one for a valid
// access token, and one that needs the permission documents.edit.
//
// node authorization/protect-routes/js/express.mjs
import express from 'express';
import { AccessTokenError, createAccessTokenVerifier, parseAuthorizationHeader } from '@lumoauth/agent';
import { LumoAuthBackend } from '@lumoauth/backend';

const issuer = `${process.env.LUMOAUTH_URL.replace(/\/+$/, '')}/orgs/${process.env.LUMOAUTH_ORG_ID}/api/v1`;
// The address of this API. A token is valid here only when its `aud` names it.
const audience = process.env.API_AUDIENCE ?? 'http://localhost:3001';
const permission = process.env.PERMISSION ?? 'documents.edit';

// The verifier checks the signature with the key set of the organization,
// and the issuer, the audience and the expiry. It keeps the key set in memory.
const verifier = createAccessTokenVerifier({ issuer, resource: audience });
// The API key asks LumoAuth about the person that the token names.
const lumo = new LumoAuthBackend({
baseUrl: process.env.LUMOAUTH_URL,
orgId: process.env.LUMOAUTH_ORG_ID,
secretKey: process.env.LUMOAUTH_API_KEY,
});

// 401 without a valid token. Otherwise `req.auth` holds the claims.
async function requireToken(req, res, next) {
const header = parseAuthorizationHeader(req.get('authorization'));
if (!header) return res.status(401).set('WWW-Authenticate', 'Bearer').json({ error: 'invalid_token' });
try {
req.auth = await verifier.verify(header.token);
next();
} catch (error) {
if (!(error instanceof AccessTokenError)) return next(error);
res.status(401).set('WWW-Authenticate', 'Bearer error="invalid_token"').json({ error: 'invalid_token' });
}
}

// 403 when the person does not hold the permission. The check runs before the handler.
const requirePermission = (slug) => async (req, res, next) => {
try {
const allowed = await lumo.permissions.check(slug, undefined, { userId: req.auth.sub });
if (!allowed) return res.status(403).json({ error: 'forbidden', permission: slug });
next();
} catch (error) {
next(error);
}
};

const app = express();
app.get('/public', (req, res) => res.json({ message: 'Hello, everybody.' }));
app.get('/me', requireToken, (req, res) => res.json({ sub: req.auth.sub }));
app.put('/documents/:id', requireToken, requirePermission(permission), (req, res) =>
res.json({ document: req.params.id, saved: true }),
);

const port = Number(process.env.PORT ?? 3001);
app.listen(port, () => console.log(`API on http://localhost:${port}`));
node authorization/protect-routes/js/express.mjs

Check the result​

Output
public, no token: 200
me, no token: 401
me, reader: 200
edit, reader: 403
edit, editor: 200
  • Send a token of the wrong kind. Express, FastAPI and Go answer 401 for a token without your API in aud.
  • Remove the role from the editor in the portal, and run try.sh again: edit, editor is now 403. The JavaScript SDK keeps each answer for five minutes by default, so Express can need that long.
  • The Test access page of the portal, under Access control, shows which role gives a person the permission.

Limits​

  • A permission check is a request to LumoAuth. LumoAuthBackend keeps answers in memory: its cache option sets how long, and cache: false asks every time.
  • Only Express, FastAPI and Go check aud. The other versions take every access token of your organization that LumoAuth accepts, also a token that names another API in aud.
  • Next.js, Spring Boot and ASP.NET Core cannot check a permission with a token that names your API in aud: LumoAuth refuses such a token for the check. Next.js then answers 401, Spring Boot answers 500, and ASP.NET Core answers 403.
  • A browser app hides buttons with the same permission, but it is your API that must refuse the request. See Show and hide UI by permission.
  • To ask about any user from a backend job, see Check a permission.