Act for a person, with consent
A person allows an agent to act for them. The agent then holds a token that names both: the person as subject, the agent as actor.
What it shows
- A person signs in to your app, Acme Calendar. The app asks for the scope
calendar:read, and receives the access token of the person. - The agent "Calendar assistant" gets its own token, and exchanges both tokens at LumoAuth (RFC 8693 token exchange).
- LumoAuth checks that the agent may act for people, and issues a new token. The person is its subject, and the agent is its actor (
act). - The calendar API reads both from the token: who asked, and who acts.
The new token holds only what the person allowed, and never more than the agent may do itself.
Before you start
- An agent with the switch May act on behalf of users. The setup script registers "Calendar assistant" with this switch and the capability
calendar:read. - An application through which the person signs in. The setup script registers Acme Calendar, with the scope
calendar:readand the redirect addresshttp://localhost:3000/auth/callback. - A person who signs in. Any user of the organization can do it.
- 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 agent does not read it. |
LUMOAUTH_CLIENT_ID | For signin.mjs: the client ID of the application "Acme Calendar". The setup script prints it. |
PORT | Optional. The port of signin.mjs, and of the redirect address that the setup script registers. Default: 3000. |
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_ACCESS_TOKEN | The access token of the person, with the scope calendar:read. signin.mjs prints it. |
CALENDAR_API_URL | Optional. The address of the API that receives the delegated token. Default: https://calendar.example.com. |
The setup script creates the scope, the application and the agent. Then signin.mjs signs the person in, as your app does: 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
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 });
signin.mjs stands in for the sign-in of your app. It prints the tokens so that the programs below can read them. Your app keeps them in the session of the person instead.
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 with the token of a person who signed in through signin.mjs. The JavaScript program was also run on a second organization, from the setup on.
- Node.js
- Python
- Go
- PHP
- Java
- C#
// An agent exchanges the token of a person for a token in which it acts for
// that person.
//
// node delegation/act-for-a-user/js/act.mjs
import { LumoAgent, decodeJwt } from '@lumoauth/agent';
const calendarApi = process.env.CALENDAR_API_URL ?? 'https://calendar.example.com';
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
const agent = new LumoAgent();
// The token that your app received when the person signed in and allowed calendar:read.
agent.delegation.setUserToken('jordan', process.env.USER_ACCESS_TOKEN);
// The person is the subject, the agent is the actor. The scope can only
// shrink, and the resource names the API that will receive the token.
const token = await agent.delegation.exchange('jordan', ['calendar:read'], { resource: calendarApi });
// What the calendar API reads after it has verified the token.
const { claims } = decodeJwt(token);
console.log(`subject: ${claims.sub} (the person)`);
console.log(`actor: ${claims.act.sub} (the agent)`);
node delegation/act-for-a-user/js/act.mjs
"""An agent exchanges the token of a person for a token in which it acts for
that person.
python delegation/act-for-a-user/python/act.py
"""
import os
from lumoauth import DelegationChain, LumoAuthAgent
calendar_api = os.environ.get("CALENDAR_API_URL", "https://calendar.example.com")
# 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)
# The token that your app received when the person signed in and allowed calendar:read.
chain.set_user_token("jordan", os.environ["USER_ACCESS_TOKEN"])
# The person is the subject, the agent is the actor. The scope can only
# shrink, and the resource names the API that will receive the token.
token = chain.exchange("jordan", ["calendar:read"], resource=calendar_api)
# What the calendar API reads after it has verified the token.
print(f"subject: {DelegationChain.get_subject(token)} (the person)")
print(f"actor: {DelegationChain.parse_actor_chain(token)[0]} (the agent)")
python delegation/act-for-a-user/python/act.py
// An agent exchanges the token of a person for a token in which it acts for
// that person.
//
// go run ./delegation/act-for-a-user/go
package main
import (
"context"
"fmt"
"log"
"os"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
ctx := context.Background()
calendarAPI := os.Getenv("CALENDAR_API_URL")
if calendarAPI == "" {
calendarAPI = "https://calendar.example.com"
}
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{})
if err != nil {
log.Fatal(err)
}
chain := lumoauth.NewDelegationChain(agent, "")
// The token that your app received when the person signed in and allowed calendar:read.
if err := chain.SetUserToken("jordan", os.Getenv("USER_ACCESS_TOKEN")); err != nil {
log.Fatal(err)
}
// The person is the subject, the agent is the actor. The scope can only
// shrink, and the resource names the API that will receive the token.
token, err := chain.ExchangeForResource(ctx, "jordan", calendarAPI, "calendar:read")
if err != nil {
log.Fatal(err)
}
// What the calendar API reads after it has verified the token.
subject, err := lumoauth.TokenSubject(token)
if err != nil {
log.Fatal(err)
}
actors, err := chain.ActorChain(token)
if err != nil {
log.Fatal(err)
}
fmt.Printf("subject: %s (the person)\n", subject)
fmt.Printf("actor: %s (the agent)\n", actors[0])
}
go run ./delegation/act-for-a-user/go
<?php
// An agent exchanges the token of a person for a token in which it acts for
// that person.
//
// php delegation/act-for-a-user/php/act.php
require __DIR__ . '/../../../php/vendor/autoload.php';
use LumoAuth\LumoAuth;
use LumoAuth\Resource\Delegation;
$calendarApi = getenv('CALENDAR_API_URL') ?: 'https://calendar.example.com';
// Reads LUMOAUTH_URL and LUMOAUTH_ORG_ID. The agent signs in with its ID and its secret.
$lumo = new LumoAuth();
$agentToken = $lumo->auth->clientCredentials(getenv('AGENT_CLIENT_ID'), getenv('AGENT_CLIENT_SECRET'))['access_token'];
// The token that your app received when the person signed in and allowed calendar:read.
$userToken = getenv('USER_ACCESS_TOKEN');
// The person is the subject, the agent is the actor. The scope can only
// shrink, and the resource names the API that will receive the token.
$token = $lumo->delegation->exchange($userToken, $agentToken, ['calendar:read'], $calendarApi)['access_token'];
// What the calendar API reads after it has verified the token.
printf("subject: %s (the person)\n", Delegation::subject($token));
printf("actor: %s (the agent)\n", Delegation::parseActorChain($token)[0]);
php delegation/act-for-a-user/php/act.php
// An agent exchanges the token of a person for a token in which it acts for
// that person.
//
// java -cp "java/lib/*" delegation/act-for-a-user/java/ActForUser.java
import io.lumoauth.LumoAgent;
import io.lumoauth.resources.DelegationResource;
import java.util.List;
public class ActForUser {
public static void main(String[] args) {
String calendarApi = System.getenv().getOrDefault("CALENDAR_API_URL", "https://calendar.example.com");
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
LumoAgent agent = LumoAgent.fromEnvironment();
// The token that your app received when the person signed in and allowed calendar:read.
String userToken = System.getenv("USER_ACCESS_TOKEN");
// The person is the subject, the agent is the actor. The scope can only
// shrink, and the resource names the API that will receive the token.
String token = agent.delegation()
.exchangeForResource(userToken, agent.accessToken(), calendarApi, List.of("calendar:read"))
.accessToken();
// What the calendar API reads after it has verified the token.
System.out.printf("subject: %s (the person)%n", DelegationResource.tokenSubject(token).orElseThrow());
System.out.printf("actor: %s (the agent)%n", DelegationResource.parseActorChain(token).get(0));
}
}
java -cp "java/lib/*" delegation/act-for-a-user/java/ActForUser.java
#:package LumoAuth@1.7.0
#:property PublishAot=false
// An agent exchanges the token of a person for a token in which it acts for
// that person.
//
// dotnet run delegation/act-for-a-user/csharp/ActForUser.cs
using LumoAuth;
using LumoAuth.Resources;
var calendarApi = Environment.GetEnvironmentVariable("CALENDAR_API_URL") ?? "https://calendar.example.com";
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
using var agent = LumoAgent.FromEnvironment();
// The token that your app received when the person signed in and allowed calendar:read.
var userToken = Environment.GetEnvironmentVariable("USER_ACCESS_TOKEN")!;
// The person is the subject, the agent is the actor. The scope can only
// shrink, and the resource names the API that will receive the token.
var answer = await agent.Client.Delegation.ExchangeForResourceAsync(
userToken, await agent.GetAccessTokenAsync(), calendarApi, ["calendar:read"]);
var token = answer.AccessToken;
// What the calendar API reads after it has verified the token.
Console.WriteLine($"subject: {DelegationResource.TokenSubject(token)} (the person)");
Console.WriteLine($"actor: {DelegationResource.ParseActorChain(token)[0]} (the agent)");
dotnet run delegation/act-for-a-user/csharp/ActForUser.cs
Check the result
subject: 01a21fe8-6814-7111-ba52-084c43664ec5 (the person)
actor: agent_agt_c6b3fbee0264c3fc (the agent)
- The subject is the ID of the person, the user who signed in. The actor is the agent ID with the prefix
agent_. - Open Audit logs under Security in the portal. The event
oauth.token_exchangenames "Calendar assistant" as the actor and the person as the target. - Turn off May act on behalf of users on the agent, and run a program again. The exchange fails with the status 403 and "Agent is not authorized to act on behalf of users".
- Your API verifies the token before it reads it: see Verify access tokens. The audience of the token is the address in
CALENDAR_API_URL.
Limits
- The scope of the new token is the scope that the person allowed, that the agent holds as a capability, and that the agent asked for. When nothing is left, the exchange fails with
invalid_scope. - The new token expires no later than the token of the person.
- The exchange shows no screen to the person. The consent is the sign-in to your app. For a decision about one action, use a just-in-time permission.
- The person signs in through an application, not through the agent. The sign-in page does not accept the client ID of an agent, so do not send the person to a consent address that the SDK builds for the agent. The programs pass the token of the person to the SDK instead.
- The programs read the token without a check of its signature. Only your API, which verifies the token, should rely on what it says.