Skip to main content

Accept a just-in-time token in your API

Make an API perform a sensitive action only with a token that a person approved for exactly this action.

RecipeReadyView source
Works with
JavaScript / TypeScriptPythonExpressFastAPI

What it shows​

  1. An agent asks for the permission to approve invoice INV-7741. A person approves, and the agent gets a just-in-time token.
  2. The agent calls your API with the token. The API asks LumoAuth about the token, and LumoAuth answers with the approved detail.
  3. The API compares the detail with the call: the action approve, on the invoice in the address. For INV-7741 it approves the invoice.
  4. For INV-7742 it refuses with the status 403. The answer names the approval that the agent must ask for.
  5. The agent completes its task. LumoAuth revokes the token, and the API refuses it from then on.

The token alone does not let the agent approve invoices. It approves one invoice, while the task runs.

Before you start​

  • The agent of Ask a person for a permission, for one task, and a person who may approve its requests. The first setup script below is the setup of that recipe.
  • An application for the API, with a client secret. The API uses it to ask LumoAuth about each token. The second setup script registers the application Invoice API.
  • Check that your plan includes just-in-time permissions in the plans matrix.
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 scripts only: an API key with the scopes admin:clients:read and admin:clients:write, and for the setup of the agent also admin:agents:read, admin:agents:write and admin:users:write. The API and the agent do not read it.
API_CLIENT_IDThe API reads it: the client ID of the application "Invoice API". The setup script prints it.
API_CLIENT_SECRETThe API reads it: the client secret of the application "Invoice API". The setup script prints it.
PORTOptional. The port of the API. Default: 3000.
AGENT_CLIENT_IDThe agent reads it: the client ID of the agent, which is its agent ID (agt_…). The setup of the agent prints it.
AGENT_CLIENT_SECRETThe agent reads it: the client secret of the agent. The setup of the agent prints it.
INVOICE_API_URLOptional. The address of the API for the agent. Default: http://localhost:3000.

The first script registers the agent of the recipe for just-in-time permissions. The second one registers the application of the API.

node approvals/just-in-time-permission/setup.mjs
node approvals/check-a-jit-token/setup.mjs
setup.mjs
// Creates the application of the invoice API. The API uses it to ask
// LumoAuth about each token that it receives. Run it again at any time.
//
// node approvals/check-a-jit-token/setup.mjs
//
// The API key needs the scopes admin:clients:read and admin:clients:write.
import { call, list, printEnv } from '../../_lib/admin.mjs';

const name = 'Invoice API';
let app = (await list('/admin/clients')).find((c) => c.name === name);
let secret;
if (app) {
// LumoAuth shows a secret once. A second run therefore makes a new secret,
// and the old one stops working.
secret = (await call('POST', `/admin/clients/${app.clientId}/rotate-secret`)).data.secret;
} else {
// A confidential application: only an application with a secret may ask
// LumoAuth about a token.
app = (await call('POST', '/admin/clients', { name, isConfidential: true, grantTypes: ['client_credentials'] })).data;
secret = app.secret;
}

console.log(`The application "${name}" is ready.`);
printEnv({ API_CLIENT_ID: app.clientId, API_CLIENT_SECRET: secret });

LumoAuth shows a secret once. A second run of a setup script therefore asks for a new secret, and the old one stops at once.

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. Each API and each agent was run, and a person approved the request in the approvals inbox of the portal. The JavaScript version was also run on a second organization, from the setup on.

approvals/check-a-jit-token/js/api.mjs
// An API that approves invoices. It accepts only a just-in-time token that a
// person approved for exactly this invoice.
//
// node approvals/check-a-jit-token/js/api.mjs
import express from 'express';
import { missingAuthorizationDetails } from '@lumoauth/mcp';

const api = `${process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev'}/orgs/${process.env.LUMOAUTH_ORG_ID}/api/v1`;
const credentials = Buffer.from(`${process.env.API_CLIENT_ID}:${process.env.API_CLIENT_SECRET}`).toString('base64');
const port = process.env.PORT ?? 3000;

// Asks LumoAuth about the token. The answer is "active" only while the token
// is unexpired and not revoked, and while its task still runs.
async function introspect(token) {
const answer = await fetch(`${api}/oauth/introspect`, {
method: 'POST',
headers: { Authorization: `Basic ${credentials}`, 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ token }),
});
if (!answer.ok) throw new Error(`LumoAuth answered ${answer.status} to the introspection`);
return answer.json();
}

const app = express();

app.post('/invoices/:id/approve', async (req, res) => {
const token = req.get('Authorization')?.match(/^Bearer (.+)$/)?.[1];
// An approval has consequences, so the API asks on every call.
const claims = token ? await introspect(token) : { active: false };
if (!claims.active || claims.jit !== true) {
return res.status(401).set('WWW-Authenticate', 'Bearer error="invalid_token"').json({ error: 'invalid_token' });
}

// The approval that this call needs: this action, on this invoice.
const needed = { type: 'invoices', actions: ['approve'], identifier: req.params.id };
if (missingAuthorizationDetails([needed], claims.authorization_details ?? []).length > 0) {
// The hint names the approval to ask for, in the form that the agent sends to LumoAuth.
return res
.status(403)
.set('WWW-Authenticate', 'Bearer error="insufficient_authorization_details"')
.set('Insufficient-Authorization-Details', Buffer.from(JSON.stringify(needed)).toString('base64'))
.json({
error: 'insufficient_authorization_details',
error_description: `The token does not approve invoice ${req.params.id}.`,
authorization_details_hint: needed,
});
}

console.log(`${req.params.id}: approved for ${claims.client_id}`);
res.json({ invoice: req.params.id, status: 'approved' });
});

app.listen(port, () => console.log(`invoice api: http://localhost:${port}`));
approvals/check-a-jit-token/js/agent.mjs
// An agent gets a just-in-time token for one invoice, and calls the invoice
// API with it: for that invoice, for another one, and after its task ends.
//
// node approvals/check-a-jit-token/js/agent.mjs
import { LumoAgent } from '@lumoauth/agent';

const apiUrl = process.env.INVOICE_API_URL ?? 'http://localhost:3000';

// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
const agent = new LumoAgent();
await agent.jit.createTask({ name: 'Pay invoice INV-7741', type: 'finance' });

// A person decides. The call waits for the decision, for 5 minutes at most.
console.log('request: waiting for a person');
const request = await agent.jit.requestPermission(
{ type: 'invoices', actions: ['approve'], identifier: 'INV-7741' },
{ justification: 'The vendor Northwind Labs asked for payment of INV-7741.' },
);
console.log(`request: ${request.status}`);
if (request.status !== 'approved') {
await agent.jit.completeTask();
process.exit(1);
}
const token = await agent.jit.getToken(request.request_id);

async function approve(invoice) {
const answer = await fetch(`${apiUrl}/invoices/${invoice}/approve`, {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
});
const body = await answer.json();
console.log(`${invoice}: ${answer.status} ${body.status ?? body.error}`);
const hint = answer.headers.get('Insufficient-Authorization-Details');
if (hint) console.log(` ask for: ${Buffer.from(hint, 'base64').toString()}`);
}

await approve('INV-7741'); // the invoice that the person approved
await approve('INV-7742'); // another invoice

// The end of the task ends the permission: LumoAuth revokes the token.
await agent.jit.completeTask();
console.log('task: completed');
await approve('INV-7741');
node approvals/check-a-jit-token/js/api.mjs
# In a second terminal:
node approvals/check-a-jit-token/js/agent.mjs

The agent stops at "waiting for a person" until somebody decides:

  1. Open the portal and go to AI Agents, then Approvals.
  2. The tab Waiting shows the request of "Invoice agent", with the record INV-7741.
  3. Open the menu … at the end of the row, and click Approve.

The comparison comes from the MCP packages of LumoAuth: missingAuthorizationDetails() in JavaScript, missing_authorization_details() in Python. It works in any API.

Check the result​

Output
request: waiting for a person
request: approved
INV-7741: 200 approved
INV-7742: 403 insufficient_authorization_details
ask for: {"type":"invoices","actions":["approve"],"identifier":"INV-7742"}
task: completed
INV-7741: 401 invalid_token
  • The API prints one line for each approved invoice, with the agent ID: INV-7741: approved for agt_….
  • The line ask for: is the decoded header Insufficient-Authorization-Details. The agent can send this detail to LumoAuth as a new request, without a change.
  • The last call gets 401: LumoAuth answers "active": false once the task is complete.
  • A token that the agent gets for itself, without an approval, also gets 401. LumoAuth answers "active": false to the API for that token.

Limits​

  • The detail cannot hold an amount. LumoAuth accepts only type, identifier, actions, privileges, locations and datatypes. Compare an amount in your API, against the invoice.
  • The API asks LumoAuth on every call. The verifiers for access tokens in the SDKs do not accept a just-in-time token: its type is JWT, not at+jwt. To check a token without a call, verify its signature against the keys of your organization, as the JIT docs describe. Such a check does not see a revocation.
  • The API does not ask for the permission. The agent does, with the detail of the hint.
  • The token is valid for 300 seconds here, and never longer than its task.