Take access back from an agent
A person sees the agents that act for them and removes one. Every token of that delegation stops working.
What it shows
- A person signs in to Acme Calendar, and the agent "Calendar assistant" gets a token to act for that person.
- The person opens AI agents acting for you in their account, and revokes the agent.
- Your app can end the same access from code: it revokes the refresh token that it received at sign-in.
- Either way, the token of the agent for that person stops at once, and the agent cannot get a new one with the old token of the person.
The agent stays registered. It keeps working for other people.
Before you start
- The application, the scopes and the agent of Act for a person, with consent. The setup script below is the setup of that recipe.
- Check that your plan includes acting for users 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:permissions:read, admin:permissions:write, admin:clients:read, admin:clients:write, admin:agents:read and admin:agents:write. The programs do not read it. |
LUMOAUTH_CLIENT_ID | The client ID of the application "Acme Calendar". The app uses it to revoke the refresh token. The setup script prints it. |
AGENT_CLIENT_ID | The client ID of the agent "Calendar assistant". The setup script prints it. |
AGENT_CLIENT_SECRET | The client secret of the agent. The setup script prints it. |
USER_ACCESS_TOKEN | The access token of the person. signin.mjs prints it. |
USER_REFRESH_TOKEN | The refresh token of the person. signin.mjs prints it. A program revokes it, so sign in again before the next run. |
The setup of the recipe for acting for a person creates the scopes, the application and the agent. Then signin.mjs signs the person in: open http://localhost:3000 and sign in. It prints the tokens of the person.
node delegation/act-for-a-user/setup.mjs
node delegation/act-for-a-user/signin.mjs
../act-for-a-user/setup.mjs
// Creates what the recipe needs: two scopes for a calendar, the application
// through which a person signs in and allows them, and an agent that may act
// for people. Run it again at any time.
//
// node delegation/act-for-a-user/setup.mjs
//
// The API key needs the scopes admin:permissions:read, admin:permissions:write,
// admin:clients:read, admin:clients:write, admin:agents:read and
// admin:agents:write.
import { call, ensure, printEnv } from '../../_lib/admin.mjs';
for (const [name, description] of [
['calendar:read', 'Read the events of your calendar.'],
['calendar:write', 'Add and change events in your calendar.'],
]) {
await ensure('/admin/scopes', (s) => s.name === name, { name, description });
}
// The person signs in here and allows both scopes. An agent can never get
// more than the person allowed.
const redirectUris = [`http://localhost:${process.env.PORT ?? 3000}/auth/callback`];
const scopes = ['openid', 'profile', 'email', 'offline_access', 'calendar:read', 'calendar:write'];
const app = await ensure('/admin/clients', (c) => c.name === 'Acme Calendar', {
name: 'Acme Calendar',
redirectUris,
isConfidential: false,
scopes,
});
// A second run with another port replaces the redirect address.
await call('PATCH', `/admin/clients/${app.clientId}`, { redirectUris, scopes });
const agent = await ensure('/admin/agents', (a) => a.name === 'Calendar assistant', {
name: 'Calendar assistant',
description: 'Reads the calendar of a person and suggests times for meetings.',
identityType: 'client_secret',
// The agent may only read, whatever the person allowed.
capabilities: ['calendar:read'],
// 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;
console.log(`The application "${app.name}" and the agent "${agent.name}" are ready.`);
printEnv({ LUMOAUTH_CLIENT_ID: app.clientId, AGENT_CLIENT_ID: agent.agentId, AGENT_CLIENT_SECRET: secret });
Revoke in the account of the person
The person does this, with no code:
- Run one of the programs of Act for a person, with consent, so that the agent holds a token for the person.
- As the person, open
https://app.lumoauth.dev/account/my-agentsand sign in. The page is AI agents acting for you, under Apps & agents in the account menu. - The card "Calendar assistant" says Tokens issued to act for you. Click Revoke on it.
- The page shows "Access revoked. The agent can no longer act on your behalf." The card leaves the page.
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 program was run after a new sign-in of the person. The revocation on the page "AI agents acting for you" was also followed, and the token of the agent became inactive. The agent still worked for another person.
- Node.js
- Python
// Your app ends the access of an agent to one person: it revokes the refresh
// token of that person. Every token that the agent got for the person stops.
//
// node delegation/revoke-an-agent/js/revoke.mjs
import { LumoAgent } from '@lumoauth/agent';
const api = `${process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev'}/orgs/${process.env.LUMOAUTH_ORG_ID}/api/v1`;
const form = (fields) => ({
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams(fields),
});
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
const agent = new LumoAgent();
agent.delegation.setUserToken('jordan', process.env.USER_ACCESS_TOKEN);
const delegated = await agent.delegation.exchange('jordan', ['calendar:read']);
// The agent asks LumoAuth whether its token for the person still works.
async function status(token) {
const answer = await fetch(
`${api}/oauth/introspect`,
form({ token, client_id: process.env.AGENT_CLIENT_ID, client_secret: process.env.AGENT_CLIENT_SECRET }),
);
return (await answer.json()).active ? 'active' : 'inactive';
}
console.log(`token of the agent for the person: ${await status(delegated)}`);
// The app received the refresh token at sign-in, so the app revokes it: a
// client can revoke only its own tokens. Acme Calendar is a public
// application, so its client ID is enough.
await fetch(
`${api}/oauth/revoke`,
form({ token: process.env.USER_REFRESH_TOKEN, token_type_hint: 'refresh_token', client_id: process.env.LUMOAUTH_CLIENT_ID }),
);
console.log('the app revoked the refresh token of the person');
console.log(`token of the agent for the person: ${await status(delegated)}`);
// The access token of the person ended with the refresh token.
try {
await agent.delegation.exchange('jordan', ['calendar:read']);
console.log('new exchange: granted');
} catch (error) {
console.log(`new exchange: refused (${error.code})`);
}
node delegation/revoke-an-agent/js/revoke.mjs
"""Your app ends the access of an agent to one person: it revokes the refresh
token of that person. Every token that the agent got for the person stops.
python delegation/revoke-an-agent/python/revoke.py
"""
import os
import requests
from lumoauth import DelegationChain, LumoAuth, LumoAuthAgent, LumoAuthApiError
api = f"{os.environ.get('LUMOAUTH_URL', 'https://app.lumoauth.dev')}/orgs/{os.environ['LUMOAUTH_ORG_ID']}/api/v1"
# 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.")
chain = DelegationChain(agent)
chain.set_user_token("jordan", os.environ["USER_ACCESS_TOKEN"])
delegated = chain.exchange("jordan", ["calendar:read"])
def status(token: str) -> str:
"""The agent asks LumoAuth whether its token for the person still works."""
answer = requests.post(
f"{api}/oauth/introspect",
data={"token": token},
auth=(os.environ["AGENT_CLIENT_ID"], os.environ["AGENT_CLIENT_SECRET"]),
timeout=10,
)
return "active" if answer.json().get("active") else "inactive"
print(f"token of the agent for the person: {status(delegated)}")
# The app received the refresh token at sign-in, so the app revokes it: a
# client can revoke only its own tokens. Acme Calendar is a public
# application, so its client ID is enough.
LumoAuth().auth.revoke(
os.environ["USER_REFRESH_TOKEN"], token_type_hint="refresh_token", client_id=os.environ["LUMOAUTH_CLIENT_ID"]
)
print("the app revoked the refresh token of the person")
print(f"token of the agent for the person: {status(delegated)}")
# The access token of the person ended with the refresh token.
try:
chain.exchange("jordan", ["calendar:read"])
print("new exchange: granted")
except LumoAuthApiError as error:
print(f"new exchange: refused ({error.code})")
python delegation/revoke-an-agent/python/revoke.py
Check the result
token of the agent for the person: active
the app revoked the refresh token of the person
token of the agent for the person: inactive
new exchange: refused (invalid_grant)
- The first line comes from introspection by the agent: its token for the person works. After the revocation the same question gets
"active": false. - The new exchange fails with
invalid_grant, because the access token of the person ended with its refresh token. - After Revoke in the account, introspection of the token of the agent also answers
"active": false. - Run a program of Act for a person, with consent with the token of another person: the agent still acts for that person.
- Open Audit logs under Security in the portal. Revoke in the account writes the event
agent.access_revoked_by_user, with the person as the actor.
Limits
- Only the client that received a token can revoke it. The agent cannot revoke the refresh token of your app: LumoAuth answers 200 and the token stays valid.
- The
revoke()method of the delegation classes in the SDKs revokes only a refresh token that the SDK received through its own consent flow, with the credentials of the agent. With a token that you passed in, it clears the local state of the SDK and ends nothing at LumoAuth. Revoke the refresh token from your app instead. - A token that the agent got for itself, without a person, does not end. To stop an agent for everybody, suspend it: see Stop an agent at once.
- Revoke in the account also ends the tasks, open requests and linked accounts of the agent for that person. The revocation of a refresh token ends only the tokens of that sign-in.
- To act for the person again, the agent needs a new token of that person, from a new sign-in.