Skip to main content

Pass identity between services

Exchange the token that a service received for a narrower token for the next service, with the person still named in it.

RecipeReadyView source
Works with
JavaScript / TypeScriptPythonGoPlain HTTP

What it shows​

  1. A person signs in to Acme Orders, service A. Its token is for Acme Orders only.
  2. Acme Orders needs stock levels from the inventory API, service B. It exchanges the token of the person at the token endpoint.
  3. The exchange names the inventory API in resource and asks for the scope inventory:read only.
  4. The inventory API verifies the new token. The subject is the same person, and client_id names Acme Orders.
  5. The first token of the person does not work at the inventory API.

The inventory API learns who the request is for. Acme Orders never passes on its own token, which works at Acme Orders and holds more scopes.

Before you start​

  • An API key for the setup script, with the scopes admin:permissions:read, admin:permissions:write, admin:clients:read and admin:clients:write.
  • A confidential application for service A. The setup script creates the application "Acme Orders" and the scope inventory:read.
  • Token exchange turned on for Acme Orders. The Admin API cannot change this switch, so use the portal:
    1. Open Applications & developer tools, Applications, and select Acme Orders.
    2. Open the Security tab.
    3. Under Token settings, turn on Enable token exchange (RFC 8693).
    4. Keep JWT (JSON Web Token) as the Access token format, so that the inventory API can verify tokens itself.
    5. Select Save token settings.
  • A user of your organization to sign in with, and a browser.
VariableValue
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
CLIENT_IDThe client ID of Acme Orders, service A. The setup script prints it.
CLIENT_SECRETThe secret of Acme Orders. The setup script prints it once, when it creates the application.
REDIRECT_URIOptional. Where LumoAuth sends the browser after sign-in. The default is http://localhost:3000/callback. Set it before the setup script too.

The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.

node oauth/token-exchange/setup.mjs
setup.mjs
// Creates what the recipe needs: the scope of the inventory API, and the
// confidential application "Acme Orders", where the person signs in. Run it
// again at any time. The client secret is shown once, when the application is
// created: add --new-secret to replace a secret that you lost.
//
// node oauth/token-exchange/setup.mjs
//
// The API key needs the scopes admin:permissions:read, admin:permissions:write,
// admin:clients:read and admin:clients:write.
import { call, ensure, list, printEnv } from '../../_lib/admin.mjs';

// Where LumoAuth sends the browser after sign-in. The programs listen there.
const redirectUri = process.env.REDIRECT_URI ?? 'http://localhost:3000/callback';

await ensure('/admin/scopes', (s) => s.name === 'inventory:read', {
name: 'inventory:read',
description: 'Read the stock levels.',
});

const name = 'Acme Orders';
let client = (await list('/admin/clients')).find((c) => c.name === name);
let secret;
if (!client) {
const created = await call('POST', '/admin/clients', {
name,
// Only a confidential application may exchange tokens.
isConfidential: true,
grantTypes: ['authorization_code', 'refresh_token'],
redirectUris: [redirectUri],
scopes: ['openid', 'profile', 'inventory:read'],
});
client = created.data;
secret = client.secret;
} else if (process.argv.includes('--new-secret')) {
secret = (await call('POST', `/admin/clients/${client.id}/rotate-secret`)).data.secret;
}

console.log(`The application "${name}" is ready. Turn on token exchange for it in the portal.`);
printEnv({ CLIENT_ID: client.clientId, ...(secret ? { CLIENT_SECRET: secret } : {}), REDIRECT_URI: redirectUri });
if (!secret) console.log('# CLIENT_SECRET was printed when the application was created. Add --new-secret to get a new one.');

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 prints an address first and waits until you have signed in there. The curl version shows both tokens through introspection, and a refused scope, instead of a verification by the API.

oauth/token-exchange/js/exchange.mjs
// Service A (Acme Orders) receives the token of a person who signed in, and
// exchanges it for a narrower token for service B (the inventory API).
// Service B verifies the new token: it names the same person.
//
// node oauth/token-exchange/js/exchange.mjs
import http from 'node:http';
import { AuthModule } from '@lumoauth/backend';
import { issuerFor, verifyAccessToken } from '@lumoauth/agent';

const baseUrl = process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev';
const issuer = issuerFor(baseUrl, process.env.LUMOAUTH_ORG_ID);
const redirectUri = process.env.REDIRECT_URI ?? 'http://localhost:3000/callback';
const { CLIENT_ID: clientId, CLIENT_SECRET: clientSecret } = process.env;
const inventory = 'https://inventory.example.com';

// 1. The person signs in to Acme Orders with the authorization code flow.
const auth = new AuthModule({ baseUrl, orgId: process.env.LUMOAUTH_ORG_ID, clientId });
const { url, codeVerifier, state } = await auth.buildAuthorizationUrl({ redirectUri, scope: 'openid profile inventory:read' });
console.log(`Open this address in a browser and sign in:\n${url}\n`);
const code = await new Promise((resolve, reject) => {
const server = http.createServer((request, response) => {
const query = new URL(request.url, redirectUri).searchParams;
response.end('Signed in. You can close this tab.');
server.close();
query.get('state') === state && query.get('code') ? resolve(query.get('code')) : reject(new Error(`Unexpected callback: ${request.url}`));
});
server.listen(new URL(redirectUri).port);
});
const { access_token: personToken } = await auth.exchangeCodeForTokens({ code, codeVerifier, redirectUri, clientSecret });
const person = await verifyAccessToken(personToken, { issuer, resource: clientId });
console.log(`Acme Orders: signed in, token for ${[person.aud].flat().join(' ')}, scope ${person.scope}`);

// 2. Acme Orders exchanges the token. It names the API in `resource` and asks
// for one scope only. The SDKs send an exchange without client
// authentication, for agents; an application sends its secret, so this
// request is a plain POST.
const response = await fetch(`${issuer}/oauth/token`, {
method: 'POST',
headers: { Authorization: `Basic ${btoa(`${clientId}:${clientSecret}`)}` },
body: new URLSearchParams({
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
subject_token: personToken,
subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',
resource: inventory,
scope: 'inventory:read',
}),
});
if (!response.ok) throw new Error(`The exchange failed: ${await response.text()}`);
const { access_token: inventoryToken, issued_token_type: issuedType } = await response.json();
console.log(`exchanged: ${issuedType}`);

// 3. The inventory API verifies the token with its own address as audience.
const claims = await verifyAccessToken(inventoryToken, { issuer, resource: inventory });
console.log(`inventory API: accepted, scope ${claims.scope}, same person: ${claims.sub === person.sub ? 'yes' : 'no'}, client ${claims.client_id === clientId ? 'Acme Orders' : claims.client_id}`);

// 4. The token of Acme Orders itself does not work at the inventory API.
try {
await verifyAccessToken(personToken, { issuer, resource: inventory });
console.log('inventory API with the token of Acme Orders: accepted');
} catch {
console.log('inventory API with the token of Acme Orders: refused');
}
node oauth/token-exchange/js/exchange.mjs

The SDKs have an exchange call, for an agent that acts for a person: it sends the token of the agent as actor_token and no client secret. An application authenticates with its own secret, so the programs send the exchange as a plain POST. The SDKs do the sign-in and verify the tokens.

Check the result​

Output
Acme Orders: signed in, token for client_3f9c2a7e5b1d4c6a8e0f2b4d6a8c0e1f, scope openid profile inventory:read
exchanged: urn:ietf:params:oauth:token-type:access_token
inventory API: accepted, scope inventory:read, same person: yes, client Acme Orders
inventory API with the token of Acme Orders: refused
  • The new token has the same sub as the token of the person, and the scope inventory:read only. Its audience is https://inventory.example.com.
  • Turn off the switch for token exchange and run a program again. The exchange answers 400 unauthorized_client.
  • Send a token that another application received as subject_token. The exchange answers invalid_grant: an application can exchange only its own tokens.
  • Ask for a scope that Acme Orders does not hold. The exchange answers invalid_scope.

Limits​

  • Only a confidential application can exchange tokens. A public application gets unauthorized_client.
  • The new token never holds a scope that the first token does not hold, and it expires no later than the first token.
  • A token without actor_token has no act claim. The token of a user or an agent can be the actor_token. The token that an application gets with client credentials is refused as actor_token with invalid_grant.
  • To let an agent act for a person, with the agent in the act claim, see Act for a person, with consent.
  • The inventory API cannot introspect the new token. Only Acme Orders, the application that holds it, can.