Skip to main content

Verify access tokens in your API

Check a token inside your service with the published keys: signature, issuer, audience, expiry and scopes.

RecipeReadyView source
Works with
JavaScript / TypeScriptPythonGoExpressFastAPIGo net/http

What it shows​

  1. The API reads the discovery document of the organization once and caches the key set.
  2. For each request, it verifies the token: the signature, the issuer, the expiry, and that the audience is this API.
  3. Each route checks its scope. A token without the scope gets 403.
  4. The API reads the subject, the scopes, the agent flag and the actor chain from the claims.
  5. A token for another API gets 401, and so does a request with no token.

The API makes no call to LumoAuth for a request. After a key rotation, the cache fetches the key set again when a token names a key ID that the cache does not hold. The API needs no restart.

Before you start​

  • The identifier of your API: an https address such as https://reports.example.com. A client names it as resource in the token request, and the token carries it as the audience. The address does not have to answer requests.
  • An API key for the setup script, with the scopes admin:permissions:read, admin:permissions:write, admin:clients:read and admin:clients:write.
  • An application that calls the API. The setup script creates the application "Reports dashboard", which may request reports:read.
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.
CLIENT_IDThe client ID of the application that calls the API. The setup script prints it.
CLIENT_SECRETThe secret of that application. The setup script prints it once, when it creates the application.
API_RESOURCEOptional. The identifier of your API, which tokens carry as the audience. The default is https://reports.example.com.
PORTOptional. The local port of the API. The default is 4000.

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

node oauth/verify-access-tokens/setup.mjs
setup.mjs
// Creates what the recipe needs: the scopes of the API, and a confidential
// application that calls the API. Run it again at any time. The client secret
// is shown once, when the application is created: add --new-secret to replace
// a secret that you lost.
//
// node oauth/verify-access-tokens/setup.mjs
//
// The API key needs the scopes admin:permissions:read, admin:permissions:write,
// admin:clients:read and admin:clients:write.
import { call, ensure, list, printEnv } from '../../_lib/admin.mjs';

for (const [name, description] of [
['reports:read', 'Read the reports.'],
['reports:write', 'Create and change reports.'],
]) {
await ensure('/admin/scopes', (s) => s.name === name, { name, description });
}

const name = 'Reports dashboard';
let client = (await list('/admin/clients')).find((c) => c.name === name);
let secret;
if (!client) {
const created = await call('POST', '/admin/clients', {
name,
isConfidential: true,
grantTypes: ['client_credentials'],
scopes: ['reports:read'],
});
client = created.data;
secret = client.secret;
} else if (process.argv.includes('--new-secret')) {
secret = (await call('POST', `/admin/clients/${client.id}/rotate-secret`)).data.secret;
}

console.log(`The application "${name}" is ready. It may request reports:read.`);
printEnv({ CLIENT_ID: client.clientId, ...(secret ? { CLIENT_SECRET: secret } : {}) });
if (!secret) console.log('# CLIENT_SECRET was printed when the application was created. Add --new-secret to get a new one.');

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. The second file starts it, asks LumoAuth for two tokens, and sends four requests.

oauth/verify-access-tokens/js/api.mjs
// The Reports API. It verifies the access token of each request with the
// published keys of the organization: no call to LumoAuth for each request.
import express from 'express';
import { AccessTokenError, accessTokenScopes, createAccessTokenVerifier, issuerFor } from '@lumoauth/agent';

// The verifier reads the discovery document once and caches the key set.
// A token with a key ID that it has not seen makes it fetch the keys again.
const verifier = createAccessTokenVerifier({
issuer: issuerFor(process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev', process.env.LUMOAUTH_ORG_ID),
// The identifier of this API. The token must name it as its audience.
resource: process.env.API_RESOURCE ?? 'https://reports.example.com',
});

// Verifies the token of the request, then checks the scope of the route.
const requireToken = (scope) => 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 });
} catch (error) {
if (!(error instanceof AccessTokenError)) return next(error);
return res.status(401).set('WWW-Authenticate', 'Bearer error="invalid_token"').json({ error: error.code, error_description: error.message });
}
if (!accessTokenScopes(req.token).includes(scope)) {
return res.status(403).json({ error: 'insufficient_scope', error_description: `Missing: ${scope}` });
}
next();
};

// What the API learned from the token: who calls, with which scopes, whether
// the caller is an agent, and who acts for the subject (the `act` claim).
const caller = (claims) => {
const actors = [];
for (let actor = claims.act; actor; actor = actor.act) actors.push(actor.sub);
return { subject: claims.sub, scopes: accessTokenScopes(claims), agent: claims.is_agent === true, actors };
};

export const app = express();
app.get('/reports', requireToken('reports:read'), (req, res) => res.json(caller(req.token)));
app.post('/reports', requireToken('reports:write'), (req, res) => res.status(201).json(caller(req.token)));
oauth/verify-access-tokens/js/try.mjs
// Starts the Reports API, then calls it with a token for this API, with a
// token for another API, and with no token.
//
// node oauth/verify-access-tokens/js/try.mjs
import { app } from './api.mjs';

const port = process.env.PORT ?? 4000;
const server = app.listen(port);

// A client asks for a token for one API: `resource` becomes the audience.
async function tokenFor(resource) {
const response = await fetch(`${process.env.LUMOAUTH_URL}/orgs/${process.env.LUMOAUTH_ORG_ID}/api/v1/oauth/token`, {
method: 'POST',
headers: { Authorization: `Basic ${btoa(`${process.env.CLIENT_ID}:${process.env.CLIENT_SECRET}`)}` },
body: new URLSearchParams({ grant_type: 'client_credentials', scope: 'reports:read', resource }),
});
if (!response.ok) throw new Error(await response.text());
return (await response.json()).access_token;
}

async function request(label, method, token) {
const response = await fetch(`http://localhost:${port}/reports`, { method, headers: token ? { Authorization: `Bearer ${token}` } : {} });
// A refused request has `error` and `error_description` in its body.
console.log(`${label} -> ${response.status} ${response.ok ? await response.text() : ''}`.trimEnd());
}

const mine = await tokenFor(process.env.API_RESOURCE ?? 'https://reports.example.com');
const other = await tokenFor('https://billing.example.com');
await request('GET /reports, token for this API', 'GET', mine);
await request('POST /reports, the same token', 'POST', mine);
await request('GET /reports, token for another API', 'GET', other);
await request('GET /reports, no token', 'GET');
server.close();
node oauth/verify-access-tokens/js/try.mjs

Check the result​

Output
GET /reports, token for this API -> 200 {"subject":"client_client_944fb2b5a6632680cf757a3053ba6e07","scopes":["reports:read"],"agent":false,"actors":[]}
POST /reports, the same token -> 403
GET /reports, token for another API -> 401
GET /reports, no token -> 401
  • The body of each refused answer has an error_description that says why. For the third request, it says that the audience is wrong.
  • The subject of this token is an application, so agent is false and actors is empty. The token of an agent has agent: true. A token from a token exchange lists the service that acts for the person in actors.

Limits​

  • This check works for JWT access tokens. An application with opaque tokens needs introspection.
  • A verified token can be revoked before it expires, and this check does not see that. Keep the lifetime of access tokens short, or introspect the token for a sensitive action.
  • For a token that is bound to a key, the verifier also needs the DPoP proof of the request. See Bind tokens to a key with DPoP.