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.
What it shows
- An agent asks for the permission to approve invoice INV-7741. A person approves, and the agent gets a just-in-time token.
- The agent calls your API with the token. The API asks LumoAuth about the token, and LumoAuth answers with the approved detail.
- The API compares the detail with the call: the action
approve, on the invoice in the address. For INV-7741 it approves the invoice. - For INV-7742 it refuses with the status 403. The answer names the approval that the agent must ask for.
- 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.
| 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 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_ID | The API reads it: the client ID of the application "Invoice API". The setup script prints it. |
API_CLIENT_SECRET | The API reads it: the client secret of the application "Invoice API". The setup script prints it. |
PORT | Optional. The port of the API. Default: 3000. |
AGENT_CLIENT_ID | The agent reads it: the client ID of the agent, which is its agent ID (agt_…). The setup of the agent prints it. |
AGENT_CLIENT_SECRET | The agent reads it: the client secret of the agent. The setup of the agent prints it. |
INVOICE_API_URL | Optional. 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.
- Node.js
- Python
// 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}`));
// 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
"""An API that approves invoices. It accepts only a just-in-time token that a
person approved for exactly this invoice.
python approvals/check-a-jit-token/python/api.py
"""
import base64
import json
import os
import requests
import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from lumoauth_fastmcp import missing_authorization_details
api = f"{os.environ.get('LUMOAUTH_URL', 'https://app.lumoauth.dev')}/orgs/{os.environ['LUMOAUTH_ORG_ID']}/api/v1"
credentials = (os.environ["API_CLIENT_ID"], os.environ["API_CLIENT_SECRET"])
port = int(os.environ.get("PORT", "3000"))
app = FastAPI()
def introspect(token: str) -> dict:
"""Asks LumoAuth about the token. The answer is "active" only while the
token is unexpired and not revoked, and while its task still runs."""
answer = requests.post(f"{api}/oauth/introspect", auth=credentials, data={"token": token}, timeout=10)
answer.raise_for_status()
return answer.json()
@app.post("/invoices/{invoice_id}/approve")
def approve(invoice_id: str, request: Request):
scheme, _, token = request.headers.get("authorization", "").partition(" ")
# An approval has consequences, so the API asks on every call.
claims = introspect(token) if scheme == "Bearer" and token else {"active": False}
if not claims.get("active") or claims.get("jit") is not True:
return JSONResponse(
{"error": "invalid_token"}, status_code=401, headers={"WWW-Authenticate": 'Bearer error="invalid_token"'}
)
# The approval that this call needs: this action, on this invoice.
needed = {"type": "invoices", "actions": ["approve"], "identifier": invoice_id}
if missing_authorization_details([needed], claims.get("authorization_details") or []):
# The hint names the approval to ask for, in the form that the agent sends to LumoAuth.
return JSONResponse(
{
"error": "insufficient_authorization_details",
"error_description": f"The token does not approve invoice {invoice_id}.",
"authorization_details_hint": needed,
},
status_code=403,
headers={
"WWW-Authenticate": 'Bearer error="insufficient_authorization_details"',
"Insufficient-Authorization-Details": base64.b64encode(json.dumps(needed, separators=(",", ":")).encode()).decode(),
},
)
print(f"{invoice_id}: approved for {claims.get('client_id')}", flush=True)
return {"invoice": invoice_id, "status": "approved"}
if __name__ == "__main__":
print(f"invoice api: http://localhost:{port}", flush=True)
uvicorn.run(app, host="127.0.0.1", port=port, log_level="warning")
"""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.
python approvals/check-a-jit-token/python/agent.py
"""
import base64
import os
import requests
from lumoauth import JITContext, LumoAuthAgent
api_url = os.environ.get("INVOICE_API_URL", "http://localhost:3000")
# Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
agent = LumoAuthAgent()
if not agent.authenticate():
raise SystemExit("The agent could not authenticate. Check its ID and its secret.")
jit = JITContext(agent)
jit.create_task(name="Pay invoice INV-7741", task_type="finance")
# A person decides. The call waits for the decision, for 5 minutes at most.
print("request: waiting for a person")
request = jit.request_permission(
{"type": "invoices", "actions": ["approve"], "identifier": "INV-7741"},
justification="The vendor Northwind Labs asked for payment of INV-7741.",
)
print(f"request: {request['status']}")
if request["status"] != "approved":
jit.complete_task()
raise SystemExit(1)
token = jit.get_token(request["request_id"])
def approve(invoice: str) -> None:
answer = requests.post(f"{api_url}/invoices/{invoice}/approve", headers={"Authorization": f"Bearer {token}"}, timeout=30)
body = answer.json()
print(f"{invoice}: {answer.status_code} {body.get('status') or body.get('error')}")
hint = answer.headers.get("Insufficient-Authorization-Details")
if hint:
print(f" ask for: {base64.b64decode(hint).decode()}")
approve("INV-7741") # the invoice that the person approved
approve("INV-7742") # another invoice
# The end of the task ends the permission: LumoAuth revokes the token.
jit.complete_task()
print("task: completed")
approve("INV-7741")
python approvals/check-a-jit-token/python/api.py
# In a second terminal:
python approvals/check-a-jit-token/python/agent.py
The agent stops at "waiting for a person" until somebody decides:
- Open the portal and go to AI Agents, then Approvals.
- The tab Waiting shows the request of "Invoice agent", with the record
INV-7741. - 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
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 headerInsufficient-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": falseonce the task is complete. - A token that the agent gets for itself, without an approval, also gets 401. LumoAuth answers
"active": falseto the API for that token.
Limits
- The detail cannot hold an amount. LumoAuth accepts only
type,identifier,actions,privileges,locationsanddatatypes. 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, notat+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.