One token for one transaction
Carry the identity of a request through several internal services, with a token that lives for seconds.
What it shows
- The setup script turns on transaction tokens in the organization.
- A request reaches your entry service, "Calendar gateway", with the access token of a person.
- The entry service exchanges that token for a transaction token. It names a purpose and narrows the scope to
calendar:read. - An internal service verifies the transaction token against the keys of the organization, and reads who the request is for and what it may do.
- LumoAuth refuses a transaction token whose scope is wider than the incoming token.
The internal services never see the access token of the person. They get a signed record of one transaction, which expires after 300 seconds.
Before you start
- Transaction tokens on. They are off by default, and the switch is for the whole organization. The setup script turns it on through the Admin API.
- An entry service with a client secret and token exchange. The setup script registers the application "Calendar gateway". Turn on its token exchange in the portal:
- Open Applications & developer tools, then Applications, and select "Calendar gateway".
- Open the tab Security.
- Turn on Enable token exchange (RFC 8693), and click Save token settings.
- The access token of a person of the organization.
node delegation/act-for-a-user/signin.mjsprints one, after the setup of Act for a person, with consent.
| 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:settings:write, admin:clients:read and admin:clients:write. The services do not read it. |
GATEWAY_CLIENT_ID | The client ID of the entry service, the application "Calendar gateway". The setup script prints it. |
GATEWAY_CLIENT_SECRET | The client secret of the entry service. The setup script prints it. |
USER_ACCESS_TOKEN | The access token that came with the request: the token of a person who signed in to an application of the organization. signin.mjs of the recipe for acting for a person prints one. |
The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.
node delegation/transaction-tokens/setup.mjs
setup.mjs
// Turns on transaction tokens in the organization, and registers the entry
// service that asks for them. Run it again at any time.
//
// node delegation/transaction-tokens/setup.mjs
//
// The API key needs the scopes admin:settings:write, admin:clients:read and
// admin:clients:write.
import { call, list, printEnv } from '../../_lib/admin.mjs';
// Transaction tokens are off by default. The switch is for the whole organization.
await call('PATCH', '/admin/settings/auth', { txn_tokens_enabled: true });
// The entry service is a confidential application: it signs in with its secret.
const name = 'Calendar gateway';
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 {
app = (await call('POST', '/admin/clients', { name, isConfidential: true, grantTypes: ['client_credentials'] })).data;
secret = app.secret;
}
console.log(`Transaction tokens are on. The application "${name}" is ready.`);
console.log('Turn on its token exchange in the portal: see "Before you start".');
printEnv({ GATEWAY_CLIENT_ID: app.clientId, GATEWAY_CLIENT_SECRET: secret });
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. Both programs were run on an organization where the setup script had turned transaction tokens on, and where the token exchange of the entry service was turned on in the portal. A transaction token was refused after 300 seconds.
- Node.js
- Python
// The entry service exchanges the token of a request for a transaction
// token. An internal service verifies the transaction token.
//
// node delegation/transaction-tokens/js/txn.mjs
import { createRemoteJWKSet, jwtVerify } from 'jose';
const issuer = `${process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev'}/orgs/${process.env.LUMOAUTH_ORG_ID}/api/v1`;
// 1. The entry service. It received USER_ACCESS_TOKEN with a request, and
// signs in with its own client ID and secret.
async function transactionToken(azd) {
const answer = await fetch(`${issuer}/oauth/token`, {
method: 'POST',
headers: {
Authorization: `Basic ${Buffer.from(`${process.env.GATEWAY_CLIENT_ID}:${process.env.GATEWAY_CLIENT_SECRET}`).toString('base64')}`,
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
subject_token: process.env.USER_ACCESS_TOKEN,
subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',
requested_token_type: 'urn:ietf:params:oauth:token-type:txn_token',
purpose: 'schedule-meeting',
// The context can only be narrower than the scope of the incoming token.
azd: JSON.stringify(azd),
}),
});
return { status: answer.status, body: await answer.json() };
}
const { status, body } = await transactionToken({ scope: 'calendar:read' });
if (status !== 200) throw new Error(`LumoAuth answered ${status}: ${body.error_description ?? body.error}`);
console.log(`transaction token: ${body.issued_token_type.split(':').pop()}, expires in ${body.expires_in} seconds`);
// 2. An internal service. It accepts only a transaction token of this
// organization: the right type, issuer and audience, and not expired.
const keys = createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`));
const { payload } = await jwtVerify(body.access_token, keys, {
issuer,
audience: `${issuer}/txn`,
typ: 'txn_token+jwt',
});
console.log(`verified: transaction ${payload.txn}, purpose ${payload.purp}`);
console.log(`for ${payload.sub}, scope ${payload.azd.scope}, requested by ${payload.req_ctx.req_wl}`);
// A context that is wider than the incoming token is refused.
const wider = await transactionToken({ scope: 'calendar:read admin:everything' });
console.log(`wider scope: ${wider.status} ${wider.body.error}`);
node delegation/transaction-tokens/js/txn.mjs
"""The entry service exchanges the token of a request for a transaction
token. An internal service verifies the transaction token.
python delegation/transaction-tokens/python/txn.py
"""
import json
import os
import jwt
import requests
issuer = f"{os.environ.get('LUMOAUTH_URL', 'https://app.lumoauth.dev')}/orgs/{os.environ['LUMOAUTH_ORG_ID']}/api/v1"
def transaction_token(azd: dict) -> requests.Response:
"""1. The entry service. It received USER_ACCESS_TOKEN with a request, and
signs in with its own client ID and secret."""
return requests.post(
f"{issuer}/oauth/token",
auth=(os.environ["GATEWAY_CLIENT_ID"], os.environ["GATEWAY_CLIENT_SECRET"]),
data={
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"subject_token": os.environ["USER_ACCESS_TOKEN"],
"subject_token_type": "urn:ietf:params:oauth:token-type:access_token",
"requested_token_type": "urn:ietf:params:oauth:token-type:txn_token",
"purpose": "schedule-meeting",
# The context can only be narrower than the scope of the incoming token.
"azd": json.dumps(azd),
},
timeout=10,
)
answer = transaction_token({"scope": "calendar:read"})
answer.raise_for_status()
body = answer.json()
print(f"transaction token: {body['issued_token_type'].split(':')[-1]}, expires in {body['expires_in']} seconds")
# 2. An internal service. It accepts only a transaction token of this
# organization: the right type, issuer and audience, and not expired.
token = body["access_token"]
if jwt.get_unverified_header(token).get("typ") != "txn_token+jwt":
raise SystemExit("not a transaction token")
key = jwt.PyJWKClient(f"{issuer}/.well-known/jwks.json").get_signing_key_from_jwt(token)
claims = jwt.decode(token, key, algorithms=["RS256", "ES256"], issuer=issuer, audience=f"{issuer}/txn")
print(f"verified: transaction {claims['txn']}, purpose {claims['purp']}")
print(f"for {claims['sub']}, scope {claims['azd']['scope']}, requested by {claims['req_ctx']['req_wl']}")
# A context that is wider than the incoming token is refused.
wider = transaction_token({"scope": "calendar:read admin:everything"})
print(f"wider scope: {wider.status_code} {wider.json()['error']}")
python delegation/transaction-tokens/python/txn.py
The SDKs of LumoAuth have no call for transaction tokens, and their verifiers accept only access tokens. The programs therefore use plain HTTP and a JWT library: jose in JavaScript, PyJWT in Python.
Check the result
transaction token: txn_token, expires in 300 seconds
verified: transaction ef1d883490dd15c4d12b907bf8c2a0e3, purpose schedule-meeting
for 01a21fdc-08a1-7ba0-b3ae-67ec52d9352d, scope calendar:read, requested by client_db63eb264e613034d6421fe9625154bc
wider scope: 400 invalid_request
- The internal service accepts the token only with the type
txn_token+jwt, the issuer of the organization, and the audience of the issuer followed by/txn. - The token carries the person in
sub, the narrowed scope inazd, the purpose inpurp, and the entry service inreq_ctx.req_wl. - Run the verification again after 300 seconds: the JWT library refuses the token as expired.
- Turn off Enable token exchange (RFC 8693) on the entry service. The exchange then fails with
unauthorized_client. - Open Audit logs under Security in the portal. Each transaction token adds the event
txn.token_issued, without the token itself.
Limits
- A transaction token is valid for 300 seconds, and never longer than the incoming token. A request cannot ask for another lifetime.
azdaccepts onlyscope, and only scopes of the incoming token. Any other member is refused withinvalid_request.- A transaction token is not an access token. Its token type is
N_A, and the LumoAuth API does not accept it. - A public application cannot ask for a transaction token. An agent can, with its own credentials.
- To carry an agent and the person that it acts for, use a delegated token instead: see Act for a person, with consent.