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.
What it shows
- A person signs in to Acme Orders, service A. Its token is for Acme Orders only.
- Acme Orders needs stock levels from the inventory API, service B. It exchanges the token of the person at the token endpoint.
- The exchange names the inventory API in
resourceand asks for the scopeinventory:readonly. - The inventory API verifies the new token. The subject is the same person, and
client_idnames Acme Orders. - 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:readandadmin: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:
- Open Applications & developer tools, Applications, and select Acme Orders.
- Open the Security tab.
- Under Token settings, turn on Enable token exchange (RFC 8693).
- Keep JWT (JSON Web Token) as the Access token format, so that the inventory API can verify tokens itself.
- Select Save token settings.
- A user of your organization to sign in with, and a browser.
| 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. |
CLIENT_ID | The client ID of Acme Orders, service A. The setup script prints it. |
CLIENT_SECRET | The secret of Acme Orders. The setup script prints it once, when it creates the application. |
REDIRECT_URI | Optional. 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.
- Node.js
- Python
- Go
- curl
// 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
"""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.
python oauth/token-exchange/python/exchange.py
"""
import base64
import hashlib
import os
import secrets
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, urlparse
import requests
from lumoauth import LumoAuth, LumoAuthTokenError, verify_access_token
lumo = LumoAuth() # reads LUMOAUTH_URL and LUMOAUTH_ORG_ID
issuer = lumo.issuer
redirect_uri = os.environ.get("REDIRECT_URI", "http://localhost:3000/callback")
client_id, client_secret = os.environ["CLIENT_ID"], os.environ["CLIENT_SECRET"]
inventory = "https://inventory.example.com"
# 1. The person signs in to Acme Orders with the authorization code flow.
verifier = secrets.token_urlsafe(32)
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
state = secrets.token_urlsafe(8)
url = lumo.auth.authorization_url(
client_id=client_id, redirect_uri=redirect_uri, scope="openid profile inventory:read", state=state, code_challenge=challenge
)
print(f"Open this address in a browser and sign in:\n{url}\n", flush=True)
class Callback(BaseHTTPRequestHandler):
def do_GET(self):
self.server.query = parse_qs(urlparse(self.path).query)
self.send_response(200)
self.end_headers()
self.wfile.write(b"Signed in. You can close this tab.")
def log_message(self, *args):
pass
server = HTTPServer(("localhost", urlparse(redirect_uri).port), Callback)
server.handle_request()
if server.query.get("state") != [state] or "code" not in server.query:
raise SystemExit(f"Unexpected callback: {server.query}")
tokens = lumo.auth.exchange_code(
server.query["code"][0], redirect_uri, client_id=client_id, client_secret=client_secret, code_verifier=verifier
)
person_token = tokens["access_token"]
person = verify_access_token(person_token, issuer=issuer, resource=client_id)
print(f"Acme Orders: signed in, token for {' '.join(person.aud)}, 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.
response = requests.post(
f"{issuer}/oauth/token",
auth=(client_id, client_secret),
data={
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"subject_token": person_token,
"subject_token_type": "urn:ietf:params:oauth:token-type:access_token",
"resource": inventory,
"scope": "inventory:read",
},
)
if not response.ok:
raise SystemExit(f"The exchange failed: {response.text}")
exchanged = response.json()
print(f"exchanged: {exchanged['issued_token_type']}")
# 3. The inventory API verifies the token with its own address as audience.
claims = verify_access_token(exchanged["access_token"], issuer=issuer, resource=inventory)
same = "yes" if claims.sub == person.sub else "no"
client = "Acme Orders" if claims.client_id == client_id else claims.client_id
print(f"inventory API: accepted, scope {claims.scope}, same person: {same}, client {client}")
# 4. The token of Acme Orders itself does not work at the inventory API.
try:
verify_access_token(person_token, issuer=issuer, resource=inventory)
print("inventory API with the token of Acme Orders: accepted")
except LumoAuthTokenError:
print("inventory API with the token of Acme Orders: refused")
python oauth/token-exchange/python/exchange.py
// 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.
//
// go run ./oauth/token-exchange/go
package main
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"strings"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
const inventory = "https://inventory.example.com"
func main() {
ctx := context.Background()
clientID, clientSecret := os.Getenv("CLIENT_ID"), os.Getenv("CLIENT_SECRET")
redirectURI := os.Getenv("REDIRECT_URI")
if redirectURI == "" {
redirectURI = "http://localhost:3000/callback"
}
// Reads LUMOAUTH_URL and LUMOAUTH_ORG_ID.
lumo, err := lumoauth.New(lumoauth.WithClientCredentials(clientID, clientSecret))
if err != nil {
log.Fatal(err)
}
issuer, _ := lumo.Issuer()
// 1. The person signs in to Acme Orders with the authorization code flow.
verifier, state := random(32), random(8)
challenge := sha256.Sum256([]byte(verifier))
authorizeURL, _ := lumo.Auth.AuthorizationURL(lumoauth.AuthorizationURLParams{
ClientID: clientID, RedirectURI: redirectURI, Scope: "openid profile inventory:read", State: state,
CodeChallenge: base64.RawURLEncoding.EncodeToString(challenge[:]),
})
fmt.Printf("Open this address in a browser and sign in:\n%s\n\n", authorizeURL)
tokens, err := lumo.Auth.ExchangeCode(ctx, lumoauth.ExchangeCodeParams{
Code: waitForCode(redirectURI, state), RedirectURI: redirectURI, ClientID: clientID, ClientSecret: clientSecret, CodeVerifier: verifier,
})
if err != nil {
log.Fatal(err)
}
person, err := lumoauth.VerifyAccessToken(ctx, tokens.AccessToken, lumoauth.AccessTokenVerifyOptions{Issuer: issuer, Resource: clientID})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Acme Orders: signed in, token for %s, scope %s\n", strings.Join(person.Audience, " "), 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.
form := url.Values{
"grant_type": {"urn:ietf:params:oauth:grant-type:token-exchange"},
"subject_token": {tokens.AccessToken},
"subject_token_type": {"urn:ietf:params:oauth:token-type:access_token"},
"resource": {inventory},
"scope": {"inventory:read"},
}
request, _ := http.NewRequest("POST", issuer+"/oauth/token", strings.NewReader(form.Encode()))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
request.SetBasicAuth(clientID, clientSecret)
response, err := http.DefaultClient.Do(request)
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
var exchanged struct {
AccessToken string `json:"access_token"`
IssuedTokenType string `json:"issued_token_type"`
Error string `json:"error_description"`
}
if json.NewDecoder(response.Body).Decode(&exchanged); exchanged.AccessToken == "" {
log.Fatalf("The exchange failed: %s %s", response.Status, exchanged.Error)
}
fmt.Printf("exchanged: %s\n", exchanged.IssuedTokenType)
// 3. The inventory API verifies the token with its own address as audience.
claims, err := lumoauth.VerifyAccessToken(ctx, exchanged.AccessToken, lumoauth.AccessTokenVerifyOptions{Issuer: issuer, Resource: inventory})
if err != nil {
log.Fatal(err)
}
same, client := "no", claims.ClientID
if claims.Subject == person.Subject {
same = "yes"
}
if client == clientID {
client = "Acme Orders"
}
fmt.Printf("inventory API: accepted, scope %s, same person: %s, client %s\n", claims.Scope, same, client)
// 4. The token of Acme Orders itself does not work at the inventory API.
if _, err := lumoauth.VerifyAccessToken(ctx, tokens.AccessToken, lumoauth.AccessTokenVerifyOptions{Issuer: issuer, Resource: inventory}); err != nil {
fmt.Println("inventory API with the token of Acme Orders: refused")
} else {
fmt.Println("inventory API with the token of Acme Orders: accepted")
}
}
// waitForCode answers one request at the redirect address and returns its code.
func waitForCode(redirectURI, state string) string {
address, _ := url.Parse(redirectURI)
codes := make(chan string)
server := &http.Server{Addr: address.Host, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Signed in. You can close this tab.")
if r.URL.Query().Get("state") != state {
log.Fatalf("Unexpected callback: %s", r.URL)
}
codes <- r.URL.Query().Get("code")
})}
go server.ListenAndServe()
code := <-codes
server.Close()
return code
}
func random(size int) string {
bytes := make([]byte, size)
rand.Read(bytes)
return base64.RawURLEncoding.EncodeToString(bytes)
}
go run ./oauth/token-exchange/go
#!/bin/sh
# Service A (Acme Orders) exchanges the token of a person who signed in for a
# narrower token for the inventory API, with curl.
#
# sh oauth/token-exchange/http/exchange.sh
#
# The script needs curl, openssl and jq.
set -eu
OAUTH="$LUMOAUTH_URL/orgs/$LUMOAUTH_ORG_ID/api/v1/oauth"
REDIRECT_URI="${REDIRECT_URI:-http://localhost:3000/callback}"
# 1. The person signs in to Acme Orders. Nothing has to listen at the redirect
# address: the browser shows an error page, and its address bar holds the code.
VERIFIER=$(openssl rand -hex 32)
CHALLENGE=$(printf '%s' "$VERIFIER" | openssl dgst -sha256 -binary | openssl base64 | tr '+/' '-_' | tr -d '=')
echo "Open this address in a browser and sign in:"
echo "$OAUTH/authorize?response_type=code&client_id=$CLIENT_ID&redirect_uri=$REDIRECT_URI&scope=openid%20profile%20inventory:read&state=recipe&code_challenge=$CHALLENGE&code_challenge_method=S256"
echo "Then paste the address that the browser ends on:"
read -r CALLBACK
CODE=$(printf '%s' "$CALLBACK" | sed -n 's/.*[?&]code=\([^&]*\).*/\1/p')
PERSON_TOKEN=$(curl --silent --show-error "$OAUTH/token" \
--user "$CLIENT_ID:$CLIENT_SECRET" \
--data "grant_type=authorization_code" \
--data "code=$CODE" \
--data-urlencode "redirect_uri=$REDIRECT_URI" \
--data "code_verifier=$VERIFIER" | jq -r .access_token)
# 2. Acme Orders exchanges the token. It authenticates with its own secret,
# names the API in `resource`, and asks for one scope only.
ANSWER=$(curl --silent --show-error "$OAUTH/token" \
--user "$CLIENT_ID:$CLIENT_SECRET" \
--data "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" \
--data-urlencode "subject_token=$PERSON_TOKEN" \
--data "subject_token_type=urn:ietf:params:oauth:token-type:access_token" \
--data-urlencode "resource=https://inventory.example.com" \
--data "scope=inventory:read")
printf '%s' "$ANSWER" | jq -c '{issued_token_type, token_type, scope, expires_in}'
# 3. Both tokens, as introspection describes them. Only Acme Orders, the
# application that holds them, may introspect them.
introspect() {
curl --silent --show-error "$OAUTH/introspect" \
--user "$CLIENT_ID:$CLIENT_SECRET" \
--data-urlencode "token=$1" | jq -c '{active, sub, aud, client_id, scope}'
}
introspect "$PERSON_TOKEN"
introspect "$(printf '%s' "$ANSWER" | jq -r .access_token)"
# 4. A scope that the application does not hold is refused.
curl --silent --show-error "$OAUTH/token" \
--user "$CLIENT_ID:$CLIENT_SECRET" \
--data "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" \
--data-urlencode "subject_token=$PERSON_TOKEN" \
--data "subject_token_type=urn:ietf:params:oauth:token-type:access_token" \
--data "scope=inventory:write"
echo
sh oauth/token-exchange/http/exchange.sh
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
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
subas the token of the person, and the scopeinventory:readonly. Its audience ishttps://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 answersinvalid_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_tokenhas noactclaim. The token of a user or an agent can be theactor_token. The token that an application gets with client credentials is refused asactor_tokenwithinvalid_grant. - To let an agent act for a person, with the agent in the
actclaim, see Act for a person, with consent. - The inventory API cannot introspect the new token. Only Acme Orders, the application that holds it, can.