Ask a person who is not in the conversation
An agent that works in the background asks a named person to approve, with the standard backchannel flow.
What it shows
- An agent builds a report at night and wants to send it for Sam Rivera. Sam is not there, so no browser can show a consent screen.
- The agent sends a backchannel request (CIBA) that names Sam, a message for Sam, and the structured detail of the action.
- Sam approves on the phone, or a reviewer approves in the approvals inbox of the portal.
- The agent polls the token endpoint, as the standard describes.
- It receives a short-lived token for exactly that detail. The token names Sam as the subject and the agent as the actor.
Before you start
- An agent with the switch May act on behalf of users turned on. The setup script registers the agent "Report agent" with that switch, and creates the user Sam Rivera.
- A person who decides. Sam can decide in the LumoAuth app on a phone. A reviewer with the permission
jit.approvecan decide in the portal. The owner of an agent cannot decide its requests, so the setup script makes a second user, Maya Chen, the owner. You can then decide as the administrator. - The setting Agents may ask users for approval (agent-initiated CIBA) of the organization, which is on by default. It is in the portal under Security, Sign-in settings, Platform security.
- Check that your plan includes acting for users and 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 script only: an API key with the scopes admin:agents:read, admin:agents:write and admin:users:write. The agent itself needs no API key. |
AGENT_CLIENT_ID | The client ID of the agent, which is its agent ID (agt_…). The setup script prints it. |
AGENT_CLIENT_SECRET | The client secret of the agent. The setup script prints it. |
USER_EMAIL | The email address of the person whom the agent asks. The setup script prints it. |
The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.
node approvals/async-authorization/setup.mjs
setup.mjs
// Creates what the recipe needs: an agent that may act for users, a user who
// owns it, and the person whom the agent asks. Run it again at any time.
//
// node approvals/async-authorization/setup.mjs
//
// The API key needs the scopes admin:agents:read, admin:agents:write and
// admin:users:write.
import { randomBytes } from 'node:crypto';
import { call, ensure, printEnv } from '../../_lib/admin.mjs';
const agent = await ensure('/admin/agents', (a) => a.name === 'Report agent', {
name: 'Report agent',
description: 'Builds the quarterly report at night, and sends it for a person.',
identityType: 'client_secret',
capabilities: ['email_access:send'],
// The switch "May act on behalf of users" of the portal.
canActOnBehalfOfUsers: true,
});
// LumoAuth shows a secret once, in the answer that creates it. On a second
// run the script therefore asks for a new secret, and the old one stops.
const secret =
agent.clientSecret ??
(await call('POST', `/admin/agents/${agent.agentId}/rotate-credentials`)).data.clientSecret;
const user = (email, name) =>
ensure('/admin/users', (u) => u.email === email, {
email,
name,
// The recipe never signs in as these users, so nobody needs the password.
password: `${randomBytes(18).toString('base64url')}#Aa1`,
emailVerified: true,
});
// The owner of an agent cannot decide its requests, and the agent belongs to
// the person who created it: you. Give it to another person, so that you can
// decide in the portal.
const owner = await user('maya.chen@example.com', 'Maya Chen');
await call('PATCH', `/admin/agents/${agent.agentId}`, { ownerId: owner.id });
// The person for whom the agent wants to send the report.
const person = await user('sam.rivera@example.com', 'Sam Rivera');
console.log(`Agent "${agent.name}" is ready. It asks ${person.email}.`);
printEnv({ AGENT_CLIENT_ID: agent.agentId, AGENT_CLIENT_SECRET: secret, USER_EMAIL: person.email });
LumoAuth shows a secret once. A second run of the setup script therefore asks for a new secret, and the old one stops at once.
Code
The SDKs have no call for this flow. The JavaScript and Python programs take the token of the agent from the SDK, and send the two requests as plain HTTP.
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 program was run, and a reviewer approved the request in the approvals inbox of the portal. The curl script was also run with a denial. The answer of the named person on a phone was not seen: the test user has no phone with the LumoAuth app.
- curl
- Python
- Node.js
#!/bin/sh
# An agent that works in the background asks a named person to approve, with
# the backchannel flow (CIBA), and polls for the token. Needs curl and jq.
#
# sh approvals/async-authorization/http/agent.sh
set -eu
API="$LUMOAUTH_URL/orgs/$LUMOAUTH_ORG_ID/api/v1"
# The agent signs in with its ID and its secret.
AGENT_TOKEN=$(curl --silent --show-error --fail "$API/oauth/token" \
--user "$AGENT_CLIENT_ID:$AGENT_CLIENT_SECRET" \
--data "grant_type=client_credentials" | jq -r .access_token)
# The request names the person, a message for them, and the detail of the action.
REQUEST=$(curl --silent --show-error "$API/oauth/bc-authorize" \
--header "Authorization: Bearer $AGENT_TOKEN" \
--data-urlencode "login_hint=$USER_EMAIL" \
--data-urlencode "binding_message=Send the Q3 report to the board list" \
--data-urlencode 'authorization_details={"type": "email_access", "actions": ["send"], "identifier": "board@example.com"}' \
--data-urlencode "requested_ttl=300")
AUTH_REQ_ID=$(printf '%s\n' "$REQUEST" | jq -r .auth_req_id)
INTERVAL=$(printf '%s\n' "$REQUEST" | jq -r .interval)
echo "request: sent to $USER_EMAIL, valid for $(printf '%s\n' "$REQUEST" | jq -r .expires_in) seconds"
# Poll the token endpoint until a person decides or the request ends.
while :; do
sleep "$INTERVAL"
ANSWER=$(curl --silent --show-error "$API/oauth/token" \
--data "grant_type=urn:openid:params:grant-type:ciba" \
--data "auth_req_id=$AUTH_REQ_ID" \
--data-urlencode "client_id=$AGENT_CLIENT_ID" \
--data-urlencode "client_secret=$AGENT_CLIENT_SECRET")
ERROR=$(printf '%s\n' "$ANSWER" | jq -r '.error // empty')
case "$ERROR" in
authorization_pending) ;;
slow_down) INTERVAL=$((INTERVAL + 5)) ;;
*) break ;;
esac
done
if [ -n "$ERROR" ]; then
# access_denied: a person refused. expired_token: nobody decided in time.
echo "decision: $ERROR"
exit 1
fi
# The token is for exactly the approved detail. It names the person and the agent.
CLAIMS=$(printf '%s\n' "$ANSWER" | jq -r '.access_token | split(".")[1] | gsub("-"; "+") | gsub("_"; "/") | @base64d')
echo "decision: approved"
echo "token: valid for $(printf '%s\n' "$ANSWER" | jq -r .expires_in) seconds"
echo "detail: $(printf '%s\n' "$ANSWER" | jq -c '.authorization_details[0]')"
echo "subject: $(printf '%s\n' "$CLAIMS" | jq -r .sub)"
echo "actor: $(printf '%s\n' "$CLAIMS" | jq -r .permissions.act.sub)"
sh approvals/async-authorization/http/agent.sh
"""An agent that works in the background asks a named person to approve, with
the backchannel flow (CIBA), and polls for the token.
python approvals/async-authorization/python/agent.py
"""
import base64
import json
import os
import time
import requests
from lumoauth import LumoAuthAgent
# 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.")
api = f"{agent.base_url}/orgs/{agent.org_id}/api/v1"
person = os.environ["USER_EMAIL"]
# The SDK has no call for this flow, so the two requests are plain HTTP.
# The request names the person, a message for them, and the detail of the action.
request = requests.post(
f"{api}/oauth/bc-authorize",
headers={"Authorization": f"Bearer {agent.access_token}"},
data={
"login_hint": person,
"binding_message": "Send the Q3 report to the board list",
"authorization_details": json.dumps(
{"type": "email_access", "actions": ["send"], "identifier": "board@example.com"}
),
"requested_ttl": 300,
},
timeout=30,
).json()
if "auth_req_id" not in request:
raise SystemExit(f"The request was refused: {request}")
print(f"request: sent to {person}, valid for {request['expires_in']} seconds")
# Poll the token endpoint until a person decides or the request ends.
interval = request["interval"]
while True:
time.sleep(interval)
answer = requests.post(
f"{api}/oauth/token",
data={
"grant_type": "urn:openid:params:grant-type:ciba",
"auth_req_id": request["auth_req_id"],
"client_id": os.environ["AGENT_CLIENT_ID"],
"client_secret": os.environ["AGENT_CLIENT_SECRET"],
},
timeout=30,
).json()
if answer.get("error") == "slow_down":
interval += 5
elif answer.get("error") != "authorization_pending":
break
if "error" in answer:
# access_denied: a person refused. expired_token: nobody decided in time.
print(f"decision: {answer['error']}")
raise SystemExit(1)
# The token is for exactly the approved detail. It names the person and the agent.
payload = answer["access_token"].split(".")[1]
claims = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
print("decision: approved")
print(f"token: valid for {answer['expires_in']} seconds")
print(f"detail: {json.dumps(answer['authorization_details'][0], separators=(',', ':'))}")
print(f"subject: {claims['sub']}")
print(f"actor: {claims['permissions']['act']['sub']}")
python approvals/async-authorization/python/agent.py
// An agent that works in the background asks a named person to approve, with
// the backchannel flow (CIBA), and polls for the token.
//
// node approvals/async-authorization/js/agent.mjs
import { setTimeout as sleep } from 'node:timers/promises';
import { LumoAgent } from '@lumoauth/agent';
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
const agent = new LumoAgent();
const api = `${agent.baseUrl}/orgs/${agent.orgId}/api/v1`;
const person = process.env.USER_EMAIL;
// The SDK has no call for this flow, so the two requests are plain HTTP.
// The request names the person, a message for them, and the detail of the action.
const request = await fetch(`${api}/oauth/bc-authorize`, {
method: 'POST',
headers: { Authorization: `Bearer ${await agent.getAccessToken()}` },
body: new URLSearchParams({
login_hint: person,
binding_message: 'Send the Q3 report to the board list',
authorization_details: JSON.stringify({ type: 'email_access', actions: ['send'], identifier: 'board@example.com' }),
requested_ttl: '300',
}),
}).then((response) => response.json());
if (!request.auth_req_id) throw new Error(`The request was refused: ${JSON.stringify(request)}`);
console.log(`request: sent to ${person}, valid for ${request.expires_in} seconds`);
// Poll the token endpoint until a person decides or the request ends.
let interval = request.interval;
let answer;
for (;;) {
await sleep(interval * 1000);
answer = await fetch(`${api}/oauth/token`, {
method: 'POST',
body: new URLSearchParams({
grant_type: 'urn:openid:params:grant-type:ciba',
auth_req_id: request.auth_req_id,
client_id: process.env.AGENT_CLIENT_ID,
client_secret: process.env.AGENT_CLIENT_SECRET,
}),
}).then((response) => response.json());
if (answer.error === 'slow_down') interval += 5;
else if (answer.error !== 'authorization_pending') break;
}
if (answer.error) {
// access_denied: a person refused. expired_token: nobody decided in time.
console.log(`decision: ${answer.error}`);
process.exit(1);
}
// The token is for exactly the approved detail. It names the person and the agent.
const claims = JSON.parse(Buffer.from(answer.access_token.split('.')[1], 'base64url'));
console.log('decision: approved');
console.log(`token: valid for ${answer.expires_in} seconds`);
console.log(`detail: ${JSON.stringify(answer.authorization_details[0])}`);
console.log(`subject: ${claims.sub}`);
console.log(`actor: ${claims.permissions.act.sub}`);
node approvals/async-authorization/js/agent.mjs
Each program polls until somebody decides. To decide as a reviewer:
- Open the portal and go to AI Agents, then Approvals.
- The tab Waiting shows the request of "Report agent" with the label CIBA, the line "For sam.rivera@example.com" and the message.
- Open the menu … at the end of the row, and click Approve or Deny.
Check the result
request: sent to sam.rivera@example.com, valid for 300 seconds
decision: approved
token: valid for 300 seconds
detail: {"type":"email_access","actions":["send"],"identifier":"board@example.com"}
subject: 01a21fc3-f09c-779a-b318-ec8f6732a862
actor: agent_agt_8c63f82df3faca58
subjectis the ID of Sam, andactoris the agent. An API that receives the token sees both.- After Deny, the program prints
decision: access_deniedand gets no token. - When nobody decides within 5 minutes, the program prints
decision: expired_token. - Open Audit logs under Security. The run adds the events
ciba.agent_initiated,ciba.agent_approvedandjit.token_issued.
Limits
- No rule approves this request automatically: a person always decides.
- The approval of the named person is not always enough. A request with a
write,delete,admin,execute,transfer,publishorrotateaction, a critical type,privileges, or an action outside the capabilities of the agent also needs a reviewer. - A request lives for 300 seconds, and for 600 seconds at most (
requested_expiry). The token lives for 60 to 900 seconds (requested_ttl), and there is no refresh token. - One request gives one token. A second poll after the token answers
invalid_grant. - An agent may send 10 requests in 5 minutes for one person.
- The API that receives the token must compare the detail with the call: see Accept a just-in-time token in your API.