Sign every request with AAuth
Give an agent an Ed25519 key and sign each HTTP request with it, so that the receiver knows which agent sent exactly this request.
What it shows
- The agent signs its own agent token, a JWT that names the key of the agent.
- The resource, the API that the agent calls, asks LumoAuth for a resource token for this agent.
- The agent sends both tokens to LumoAuth in a signed request, and receives an auth token for the resource.
- The agent signs one request to the resource: the method, the address, a digest of the body and the
Authorizationheader. - The resource checks the auth token and the signature. When one byte of the body changes, the resource refuses the request.
Each program plays both parts, the agent and the resource, so that you can read the whole exchange in one file. In your own system, the two parts run on different servers.
Before you start
AAuth agents and resources are registered in the portal. The Admin API has no call for them.
First run the setup script below. It creates two Ed25519 key pairs, one for the agent and one for the resource. It writes the private keys to files in your home folder and prints the public keys.
Then register the resource:
- In the portal, open AI Agents, then Agents, then the AAuth resources tab. Click Register resource.
- Enter the Resource name
Supplier directory APIand the Resource identifierhttps://suppliers.example.com. - Under Public keys, paste the public key of the resource that the setup script printed.
- Under Scopes, add the scope
suppliers:readwith the description "Read the supplier directory". - Click Register resource.
Then register the agent:
- On the Agents page, click Register agent. Enter the Agent name
Supplier lookup agentand click Next: how it proves its identity. - Choose AAuth. Enter the Agent identifier
https://supplier-lookup.example.com, and paste the key set of the agent into JWKS (inline). Click Next: what it may do. - Under Acting for people, leave User-in-the-loop authorization switched off. Enter
suppliers:readin Pre-authorized scopes. - Click Register agent.
The agent acts alone here, so no person is asked. An agent that acts alone receives only the scopes listed in its Pre-authorized scopes.
| 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. |
AGENT_PRIVATE_KEY | The Ed25519 private key of the agent, as PEM. The setup script writes it to a file and prints the command that sets the variable. |
RESOURCE_PRIVATE_KEY | The Ed25519 private key of the resource, the API that the agent calls. The setup script writes it to a file as well. |
AAUTH_AGENT | Optional. The agent identifier that you registered. Default: https://supplier-lookup.example.com. |
AAUTH_RESOURCE | Optional. The resource identifier that you registered. Default: https://suppliers.example.com. |
The setup script creates the two key pairs and prints the public keys for the portal. It calls no API and needs no API key.
node agents/aauth-signed-requests/setup.mjs
setup.mjs
// Creates the two key pairs of this recipe: one for the agent and one for
// the resource, the API that the agent calls. The private keys go to files
// outside the repository. The script prints the public keys, which you
// register in the portal as the page describes. It calls no API.
//
// node agents/aauth-signed-requests/setup.mjs
//
// The files are written to the folder that AAUTH_KEY_DIR names. Without that
// variable, the folder is your home folder. A second run keeps the keys.
import { createPublicKey, generateKeyPairSync } from 'node:crypto';
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
const dir = process.env.AAUTH_KEY_DIR ?? homedir();
// Returns the file of a private key and its public half as a JWK.
function key(name) {
const file = join(dir, `aauth-${name}-key.pem`);
if (!existsSync(file)) {
const pem = generateKeyPairSync('ed25519').privateKey.export({ type: 'pkcs8', format: 'pem' });
writeFileSync(file, pem, { mode: 0o600 });
}
const { kty, crv, x } = createPublicKey(readFileSync(file, 'utf8')).export({ format: 'jwk' });
return { file, jwk: { kty, crv, x, use: 'sig', kid: 'key-1' } };
}
const agent = key('agent');
const resource = key('resource');
console.log('Public keys of the agent, for the field "JWKS (inline)":');
console.log(JSON.stringify({ keys: [agent.jwk] }));
console.log('\nPublic key of the resource, for the box under "Public keys":');
console.log(JSON.stringify(resource.jwk));
console.log('\n# Set these before you run the recipe:');
console.log(`export AGENT_PRIVATE_KEY="$(cat '${agent.file}')"`);
console.log(`export RESOURCE_PRIVATE_KEY="$(cat '${resource.file}')"`);
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 plays the agent and the resource. The signed request goes to the check of the resource inside the program, not over the network.
- Node.js
- Python
- Go
- PHP
- Java
- C#
// An agent gets an AAuth token for one API and signs a request with its own
// key. The API, which AAuth calls the resource, verifies the token and the
// signature. One program plays both parts, so that you can read the whole
// exchange in one file.
//
// node agents/aauth-signed-requests/js/aauth.mjs
import { createPrivateKey, createPublicKey, randomUUID, sign } from 'node:crypto';
import {
AAuthClient,
buildSignatureBase,
contentDigestSha256,
signRequest,
verifyAuthToken,
verifySignatureBase,
} from '@lumoauth/agent';
const AGENT = process.env.AAUTH_AGENT ?? 'https://supplier-lookup.example.com';
const RESOURCE = process.env.AAUTH_RESOURCE ?? 'https://suppliers.example.com';
const KEY_ID = 'key-1';
// Reads LUMOAUTH_URL and LUMOAUTH_ORG_ID.
const agent = new AAuthClient({ agentIdentifier: AGENT, privateKeyPem: process.env.AGENT_PRIVATE_KEY, kid: KEY_ID });
const base64url = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');
// ----- The agent -----
// 1. The agent token says which key signs the requests of the agent. The
// agent signs this JWT itself, with a key of its registered key set.
function agentToken() {
const now = Math.floor(Date.now() / 1000);
const header = { typ: 'agent+jwt', alg: 'EdDSA', kid: KEY_ID };
const claims = {
iss: AGENT,
sub: `${AGENT}/session/main`,
aud: agent.issuer,
iat: now,
exp: now + 300,
jti: randomUUID(),
cnf: { jwk: agent.publicJwk },
};
const input = `${base64url(header)}.${base64url(claims)}`;
const signature = sign(null, Buffer.from(input), createPrivateKey(process.env.AGENT_PRIVATE_KEY));
return `${input}.${signature.toString('base64url')}`;
}
// ----- The resource -----
// 2. The resource asks LumoAuth for a resource token. The token names the
// agent, the key of the agent and the scope that the resource allows.
// The resource signs this request with its own key.
async function resourceToken(agentIdentifier, agentKeyThumbprint) {
const url = `${agent.issuer}/aauth/resource/token`;
const body = JSON.stringify({
resource: RESOURCE,
agent: agentIdentifier,
agent_jkt: agentKeyThumbprint,
scope: 'suppliers:read',
});
const headers = signRequest(process.env.RESOURCE_PRIVATE_KEY, 'POST', url, { body });
const answer = await fetch(url, { method: 'POST', headers, body });
if (!answer.ok) throw new Error(`The resource token was refused: ${answer.status} ${await answer.text()}`);
return (await answer.json()).resource_token;
}
// 5. The resource verifies a request. It checks the auth token, the digest
// of the body, and that the key of the token signed this request.
async function verifyRequest({ method, url, headers, body }) {
let claims;
try {
const token = headers.Authorization.replace(/^Bearer /, '');
claims = await verifyAuthToken(token, { issuer: agent.issuer, resource: RESOURCE });
} catch (error) {
return `refused: ${error.message}`;
}
if (headers['Content-Digest'] !== contentDigestSha256(body)) return 'refused: the body does not match its digest';
// The signature must cover the parts that matter, and it must be recent.
const [, list, created, nonce] = headers['Signature-Input'].match(/^sig1=\(([^)]*)\);created=(\d+);nonce="([^"]+)"$/);
const components = list.split(' ').map((name) => name.replaceAll('"', ''));
for (const name of ['@method', '@authority', '@path', 'content-digest', 'authorization']) {
if (!components.includes(name)) return `refused: the signature does not cover ${name}`;
}
if (Math.abs(Date.now() / 1000 - Number(created)) > 60) return 'refused: the signature is too old';
// Rebuild the text that the agent signed, from the request as it arrived.
const { host, pathname } = new URL(url);
const values = {
'@method': method,
'@authority': host,
'@path': pathname,
'signature-key': headers['Signature-Key'] ?? '',
'content-digest': headers['Content-Digest'],
'content-type': headers['Content-Type'],
authorization: headers.Authorization,
};
const base = buildSignatureBase(components, values, Number(created), nonce);
const signature = headers.Signature.slice('sig1=:'.length, -1);
const key = createPublicKey({ key: claims.cnf.jwk, format: 'jwk' });
if (!verifySignatureBase(base, signature, key)) return 'refused: the signature does not fit the key of the token';
return `accepted, agent ${claims.agent}, scope ${claims.scope}`;
}
// ----- The exchange -----
// 3. The agent sends both tokens to LumoAuth in a signed request, and
// receives an auth token for this resource. The token carries its key.
const authorization = await agent.requestAuthToken({
agentToken: agentToken(),
resourceToken: await resourceToken(AGENT, agent.publicJwkThumbprint),
});
if ('authorizationRequired' in authorization) throw new Error('A person must approve first. See "Before you start".');
console.log(`auth token: ${authorization.tokenType}, valid for ${authorization.expiresIn} seconds`);
// 4. The agent signs one request: the method, the address, the digest of the
// body and the Authorization header.
const url = `${RESOURCE}/v1/suppliers/search`;
const body = JSON.stringify({ name: 'Northwind Labs' });
const bearer = `Bearer ${authorization.authToken}`;
const headers = { Authorization: bearer, ...agent.signRequest('POST', url, { body, authorization: bearer }) };
console.log(`signed: ${headers['Signature-Input'].match(/\(([^)]*)\)/)[1].replaceAll('"', '')}`);
console.log(`request as signed: ${await verifyRequest({ method: 'POST', url, headers, body })}`);
// 6. Somebody changes the body on the way. The signature still covers the
// old digest, so the resource refuses the request.
const changed = body.replace('Northwind Labs', 'Northwind Labz');
console.log(`request after a change: ${await verifyRequest({ method: 'POST', url, headers, body: changed })}`);
node agents/aauth-signed-requests/js/aauth.mjs
"""An agent gets an AAuth token for one API and signs a request with its own
key. The API, which AAuth calls the resource, verifies the token and the
signature. One program plays both parts, so that you can read the whole
exchange in one file.
python agents/aauth-signed-requests/python/aauth.py
"""
import base64
import hashlib
import json
import os
import re
import time
import uuid
import jwt # PyJWT: signs the agent token and checks the auth token
import requests
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat, load_pem_private_key
from lumoauth import AAuthClient
AGENT = os.environ.get("AAUTH_AGENT", "https://supplier-lookup.example.com")
RESOURCE = os.environ.get("AAUTH_RESOURCE", "https://suppliers.example.com")
KEY_ID = "key-1"
AGENT_KEY = os.environ["AGENT_PRIVATE_KEY"]
# Reads LUMOAUTH_URL and LUMOAUTH_ORG_ID.
agent = AAuthClient(AGENT, AGENT_KEY, kid=KEY_ID)
issuer = agent.get_issuer()
def b64url(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def digest(body: bytes) -> str:
return "sha-256=:" + base64.b64encode(hashlib.sha256(body).digest()).decode() + ":"
# The public key of the agent as a JWK, and its RFC 7638 thumbprint.
public = load_pem_private_key(AGENT_KEY.encode(), None).public_key()
agent_jwk = {"crv": "Ed25519", "kty": "OKP", "x": b64url(public.public_bytes(Encoding.Raw, PublicFormat.Raw))}
agent_thumbprint = b64url(hashlib.sha256(json.dumps(agent_jwk, separators=(",", ":")).encode()).digest())
# ----- The agent -----
# 1. The agent token says which key signs the requests of the agent. The
# agent signs this JWT itself, with a key of its registered key set.
def agent_token() -> str:
now = int(time.time())
claims = {
"iss": AGENT,
"sub": f"{AGENT}/session/main",
"aud": issuer,
"iat": now,
"exp": now + 300,
"jti": str(uuid.uuid4()),
"cnf": {"jwk": agent_jwk},
}
return jwt.encode(claims, AGENT_KEY, algorithm="EdDSA", headers={"typ": "agent+jwt", "kid": KEY_ID})
# ----- The resource -----
# The resource signs its requests to LumoAuth with its own key.
resource = AAuthClient(RESOURCE, os.environ["RESOURCE_PRIVATE_KEY"])
issuer_keys = jwt.PyJWKClient(f"{issuer}/aauth/jwks.json")
# 2. The resource asks LumoAuth for a resource token. The token names the
# agent, the key of the agent and the scope that the resource allows.
def resource_token(agent_identifier: str, agent_key_thumbprint: str) -> str:
url = f"{issuer}/aauth/resource/token"
body = json.dumps({
"resource": RESOURCE,
"agent": agent_identifier,
"agent_jkt": agent_key_thumbprint,
"scope": "suppliers:read",
}).encode()
answer = requests.post(url, data=body, headers=resource.sign_request("POST", url, body=body), timeout=30)
if not answer.ok:
raise RuntimeError(f"The resource token was refused: {answer.status_code} {answer.text}")
return answer.json()["resource_token"]
# 5. The resource verifies a request. It checks the auth token, the digest
# of the body, and that the key of the token signed this request.
def verify_request(method: str, url: str, headers: dict, body: bytes) -> str:
try:
token = headers["Authorization"].removeprefix("Bearer ")
if jwt.get_unverified_header(token).get("typ") != "auth+jwt":
return "refused: this is not an auth token"
key = issuer_keys.get_signing_key_from_jwt(token)
claims = jwt.decode(token, key, algorithms=["RS256"], audience=RESOURCE, issuer=issuer)
except jwt.PyJWTError as error:
return f"refused: {error}"
if headers["Content-Digest"] != digest(body):
return "refused: the body does not match its digest"
# The signature must cover the parts that matter, and it must be recent.
listed, created, nonce = re.fullmatch(r'sig1=\(([^)]*)\);created=(\d+);nonce="([^"]+)"', headers["Signature-Input"]).groups()
components = listed.replace('"', "").split(" ")
for name in ("@method", "@authority", "@path", "content-digest", "authorization"):
if name not in components:
return f"refused: the signature does not cover {name}"
if abs(time.time() - int(created)) > 60:
return "refused: the signature is too old"
# Rebuild the text that the agent signed, from the request as it arrived.
parts = requests.utils.urlparse(url)
values = {
"@method": method,
"@authority": parts.netloc,
"@path": parts.path,
"signature-key": headers.get("Signature-Key", ""),
"content-digest": headers["Content-Digest"],
"content-type": headers["Content-Type"],
"authorization": headers["Authorization"],
}
lines = [f'"{name}": {values[name]}' for name in components]
lines.append(f'"@signature-params": ({listed});created={created};nonce="{nonce}"')
signature = base64.urlsafe_b64decode(headers["Signature"][len("sig1=:"):-1] + "==")
key = Ed25519PublicKey.from_public_bytes(base64.urlsafe_b64decode(claims["cnf"]["jwk"]["x"] + "=="))
try:
key.verify(signature, "\n".join(lines).encode())
except Exception:
return "refused: the signature does not fit the key of the token"
return f"accepted, agent {claims['agent']}, scope {claims['scope']}"
# ----- The exchange -----
# 3. The agent sends both tokens to LumoAuth in a signed request, and
# receives an auth token for this resource. The token carries its key.
# The scope of the auth token comes from the resource token.
authorization = agent.request_authorization(
resource_token(AGENT, agent_thumbprint),
"suppliers:read",
agent_token=agent_token(),
)
if authorization.get("authorization_required"):
raise SystemExit('A person must approve first. See "Before you start".')
print(f"auth token: {authorization['token_type']}, valid for {authorization['expires_in']} seconds")
# 4. The agent signs one request: the method, the address, the digest of the
# body and the Authorization header.
url = f"{RESOURCE}/v1/suppliers/search"
body = json.dumps({"name": "Northwind Labs"}).encode()
bearer = f"Bearer {authorization['auth_token']}"
headers = {"Authorization": bearer, **agent.sign_request("POST", url, body=body, authorization=bearer)}
print("signed: " + re.search(r"\(([^)]*)\)", headers["Signature-Input"])[1].replace('"', ""))
print(f"request as signed: {verify_request('POST', url, headers, body)}")
# 6. Somebody changes the body on the way. The signature still covers the
# old digest, so the resource refuses the request.
changed = body.replace(b"Northwind Labs", b"Northwind Labz")
print(f"request after a change: {verify_request('POST', url, headers, changed)}")
python agents/aauth-signed-requests/python/aauth.py
// An agent gets an AAuth token for one API and signs a request with its own
// key. The API, which AAuth calls the resource, verifies the token and the
// signature. One program plays both parts, so that you can read the whole
// exchange in one file.
//
// go run ./agents/aauth-signed-requests/go
package main
import (
"bytes"
"context"
"crypto"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"math"
"net/http"
"os"
"regexp"
"slices"
"strconv"
"strings"
"time"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
const keyID = "key-1"
var (
agentID = env("AAUTH_AGENT", "https://supplier-lookup.example.com")
resourceID = env("AAUTH_RESOURCE", "https://suppliers.example.com")
ctx = context.Background()
)
func main() {
// Reads LUMOAUTH_URL and LUMOAUTH_ORG_ID.
agent, err := lumoauth.NewAAuthClient(lumoauth.AAuthConfig{
AgentIdentifier: agentID,
PrivateKeyPEM: os.Getenv("AGENT_PRIVATE_KEY"),
Kid: keyID,
})
check(err)
thumbprint, err := agent.PublicJWKThumbprint()
check(err)
// 3. The agent sends both tokens to LumoAuth in a signed request, and
// receives an auth token for this resource. The token carries its key.
// The scope of the auth token comes from the resource token.
authorization, err := agent.RequestAuthToken(ctx, lumoauth.AuthTokenParams{
AgentToken: agentToken(agent),
ResourceToken: resourceToken(agent.Issuer(), agentID, thumbprint),
})
check(err)
if authorization.AuthorizationRequired {
log.Fatal(`A person must approve first. See "Before you start".`)
}
fmt.Printf("auth token: %s, valid for %d seconds\n", authorization.TokenType, authorization.ExpiresIn)
// 4. The agent signs one request: the method, the address, the digest of
// the body and the Authorization header.
url := resourceID + "/v1/suppliers/search"
body := []byte(`{"name":"Northwind Labs"}`)
bearer := "Bearer " + authorization.AuthToken
headers, err := agent.SignRequest("POST", url, lumoauth.SignOptions{Body: body, Authorization: bearer})
check(err)
headers["Authorization"] = bearer
fmt.Println("signed:", strings.ReplaceAll(regexp.MustCompile(`\(([^)]*)\)`).FindStringSubmatch(headers["Signature-Input"])[1], `"`, ""))
fmt.Println("request as signed:", verifyRequest(agent.Issuer(), "POST", url, headers, body))
// 6. Somebody changes the body on the way. The signature still covers the
// old digest, so the resource refuses the request.
changed := bytes.Replace(body, []byte("Northwind Labs"), []byte("Northwind Labz"), 1)
fmt.Println("request after a change:", verifyRequest(agent.Issuer(), "POST", url, headers, changed))
}
// ----- The agent -----
// 1. The agent token says which key signs the requests of the agent. The
// agent signs this JWT itself, with a key of its registered key set.
func agentToken(agent *lumoauth.AAuthClient) string {
jwk, err := agent.PublicJWK()
check(err)
now := time.Now().Unix()
header := map[string]any{"typ": "agent+jwt", "alg": "EdDSA", "kid": keyID}
claims := map[string]any{
"iss": agentID,
"sub": agentID + "/session/main",
"aud": agent.Issuer(),
"iat": now,
"exp": now + 300,
"jti": rand.Text(),
"cnf": map[string]any{"jwk": jwk},
}
input := segment(header) + "." + segment(claims)
key, err := lumoauth.LoadPrivateKey(os.Getenv("AGENT_PRIVATE_KEY"))
check(err)
signature, err := key.Sign(rand.Reader, []byte(input), crypto.Hash(0))
check(err)
return input + "." + base64.RawURLEncoding.EncodeToString(signature)
}
// ----- The resource -----
// 2. The resource asks LumoAuth for a resource token. The token names the
// agent, the key of the agent and the scope that the resource allows.
// The resource signs this request with its own key.
func resourceToken(issuer, agentIdentifier, agentKeyThumbprint string) string {
url := issuer + "/aauth/resource/token"
body, _ := json.Marshal(map[string]string{
"resource": resourceID,
"agent": agentIdentifier,
"agent_jkt": agentKeyThumbprint,
"scope": "suppliers:read",
})
headers, err := lumoauth.SignRequest(os.Getenv("RESOURCE_PRIVATE_KEY"), "POST", url, lumoauth.SignOptions{Body: body})
check(err)
request, _ := http.NewRequest("POST", url, bytes.NewReader(body))
for name, value := range headers {
request.Header.Set(name, value)
}
answer, err := http.DefaultClient.Do(request)
check(err)
defer answer.Body.Close()
var result struct {
ResourceToken string `json:"resource_token"`
}
if answer.StatusCode != http.StatusOK {
log.Fatalf("The resource token was refused: %s", answer.Status)
}
check(json.NewDecoder(answer.Body).Decode(&result))
return result.ResourceToken
}
// 5. The resource verifies a request. It checks the auth token, the digest
// of the body, and that the key of the token signed this request.
func verifyRequest(issuer, method, url string, headers map[string]string, body []byte) string {
token := strings.TrimPrefix(headers["Authorization"], "Bearer ")
claims, err := lumoauth.VerifyAuthToken(ctx, token, lumoauth.VerifyOptions{Issuer: issuer, Resource: resourceID})
if err != nil {
return "refused: " + err.Error()
}
if headers["Content-Digest"] != lumoauth.ContentDigestSHA256(body) {
return "refused: the body does not match its digest"
}
// The signature must cover the parts that matter, and it must be recent.
match := regexp.MustCompile(`^sig1=\(([^)]*)\);created=(\d+);nonce="[^"]+"$`).FindStringSubmatch(headers["Signature-Input"])
if match == nil {
return "refused: the signature input has an unknown form"
}
components := strings.Fields(strings.ReplaceAll(match[1], `"`, ""))
for _, name := range []string{"@method", "@authority", "@path", "content-digest", "authorization"} {
if !slices.Contains(components, name) {
return "refused: the signature does not cover " + name
}
}
created, _ := strconv.ParseInt(match[2], 10, 64)
if math.Abs(float64(time.Now().Unix()-created)) > 60 {
return "refused: the signature is too old"
}
// The SDK rebuilds the text that the agent signed, from the request as
// it arrived, and checks it with the key of the token.
request, _ := http.NewRequest(method, url, bytes.NewReader(body))
for name, value := range headers {
request.Header.Set(name, value)
}
if err := claims.VerifyProofOfPossession(request, body); err != nil {
return "refused: the signature does not fit the key of the token"
}
return fmt.Sprintf("accepted, agent %s, scope %s", claims.Agent, claims.Scope)
}
func segment(value any) string {
data, _ := json.Marshal(value)
return base64.RawURLEncoding.EncodeToString(data)
}
func env(name, fallback string) string {
if value := os.Getenv(name); value != "" {
return value
}
return fallback
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
go run ./agents/aauth-signed-requests/go
<?php
// An agent gets an AAuth token for one API and signs a request with its own
// key. The API, which AAuth calls the resource, verifies the token and the
// signature. One program plays both parts, so that you can read the whole
// exchange in one file.
//
// php agents/aauth-signed-requests/php/aauth.php
require __DIR__ . '/../../../php/vendor/autoload.php';
use LumoAuth\AAuth\AAuthClient;
use LumoAuth\AAuth\Signer;
use LumoAuth\LumoAuth;
const KEY_ID = 'key-1';
$agentId = getenv('AAUTH_AGENT') ?: 'https://supplier-lookup.example.com';
$resourceId = getenv('AAUTH_RESOURCE') ?: 'https://suppliers.example.com';
// Reads LUMOAUTH_URL and LUMOAUTH_ORG_ID.
$lumo = new LumoAuth();
$agent = new AAuthClient(getenv('AGENT_PRIVATE_KEY'), $lumo->http());
$issuer = $agent->issuer();
function json(array $value): string
{
return json_encode($value, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
}
function decode64(string $text): string
{
return base64_decode(strtr($text, '-_', '+/'));
}
// The RFC 7638 thumbprint of an Ed25519 key: its members in this order, without spaces.
function thumbprint(array $jwk): string
{
return Signer::base64url(hash('sha256', json(['crv' => $jwk['crv'], 'kty' => $jwk['kty'], 'x' => $jwk['x']]), true));
}
// ----- The agent -----
// 1. The agent token says which key signs the requests of the agent. The
// agent signs this JWT itself, with a key of its registered key set.
function agentToken(string $agentId, string $issuer, array $jwk): string
{
$now = time();
$header = ['typ' => 'agent+jwt', 'alg' => 'EdDSA', 'kid' => KEY_ID];
$claims = [
'iss' => $agentId,
'sub' => "$agentId/session/main",
'aud' => $issuer,
'iat' => $now,
'exp' => $now + 300,
'jti' => bin2hex(random_bytes(16)),
'cnf' => ['jwk' => $jwk],
];
$input = Signer::base64url(json($header)) . '.' . Signer::base64url(json($claims));
// The SDK signs requests, not JWTs, so ext-sodium signs the token. The
// last 32 bytes of the PKCS#8 key are the Ed25519 seed.
$seed = substr(decode64(preg_replace('/-----[^-]+-----|\s+/', '', getenv('AGENT_PRIVATE_KEY'))), -32);
$secret = sodium_crypto_sign_secretkey(sodium_crypto_sign_seed_keypair($seed));
return $input . '.' . Signer::base64url(sodium_crypto_sign_detached($input, $secret));
}
// ----- The resource -----
// The resource signs its requests to LumoAuth with its own key.
function resourcePost(string $url, array $data): array
{
global $lumo;
$body = json($data);
$headers = (new Signer(getenv('RESOURCE_PRIVATE_KEY')))->sign('POST', $url, $body);
return $lumo->http()->request('POST', $url, headers: $headers, auth: false, rawBody: $body);
}
// 2. The resource asks LumoAuth for a resource token. The token names the
// agent, the key of the agent and the scope that the resource allows.
function resourceToken(string $agentIdentifier, string $agentKeyThumbprint): string
{
global $issuer, $resourceId;
$answer = resourcePost("$issuer/aauth/resource/token", [
'resource' => $resourceId,
'agent' => $agentIdentifier,
'agent_jkt' => $agentKeyThumbprint,
'scope' => 'suppliers:read',
]);
return $answer['resource_token'];
}
// 5. The resource verifies a request. It checks the auth token, the digest
// of the body, and that the key of the token signed this request.
function verifyRequest(string $method, string $url, array $headers, string $body): string
{
global $issuer, $resourceId;
// LumoAuth checks the token: its signature, issuer, audience, expiry,
// and whether it was revoked. The PHP SDK has no local verifier.
// The body names the resource, because LumoAuth finds its key by that name.
$token = substr($headers['Authorization'], strlen('Bearer '));
$answer = resourcePost("$issuer/aauth/auth/token/verify", ['resource' => $resourceId, 'auth_token' => $token]);
if (!($answer['active'] ?? false)) {
return 'refused: ' . ($answer['error'] ?? 'the token is not valid');
}
if ($headers['Content-Digest'] !== Signer::contentDigest($body)) {
return 'refused: the body does not match its digest';
}
// The signature must cover the parts that matter, and it must be recent.
if (!preg_match('/^sig1=\(([^)]*)\);created=(\d+);nonce="([^"]+)"$/', $headers['Signature-Input'], $input)) {
return 'refused: the signature input has an unknown form';
}
[, $listed, $created, $nonce] = $input;
$components = explode(' ', str_replace('"', '', $listed));
foreach (['@method', '@authority', '@path', 'content-digest', 'authorization'] as $name) {
if (!in_array($name, $components, true)) {
return "refused: the signature does not cover $name";
}
}
if (abs(time() - (int) $created) > 60) {
return 'refused: the signature is too old';
}
// The token carries the key of the agent, and LumoAuth named its thumbprint.
$jwk = json_decode(decode64(explode('.', $token)[1]), true)['cnf']['jwk'];
if (thumbprint($jwk) !== $answer['cnf_jkt']) {
return 'refused: the key in the token does not match';
}
// Rebuild the text that the agent signed, from the request as it arrived.
$parts = parse_url($url);
$values = [
'@method' => $method,
'@authority' => $parts['host'] . (isset($parts['port']) ? ':' . $parts['port'] : ''),
'@path' => $parts['path'],
'signature-key' => $headers['Signature-Key'] ?? '',
'content-digest' => $headers['Content-Digest'],
'content-type' => $headers['Content-Type'],
'authorization' => $headers['Authorization'],
];
$lines = array_map(fn (string $name): string => "\"$name\": {$values[$name]}", $components);
$lines[] = "\"@signature-params\": ($listed);created=$created;nonce=\"$nonce\"";
$signature = decode64(substr($headers['Signature'], strlen('sig1=:'), -1));
if (!sodium_crypto_sign_verify_detached($signature, implode("\n", $lines), decode64($jwk['x']))) {
return 'refused: the signature does not fit the key of the token';
}
return "accepted, agent {$answer['agent']}, scope {$answer['scope']}";
}
// ----- The exchange -----
// 3. The agent sends both tokens to LumoAuth in a signed request, and
// receives an auth token for this resource. The token carries its key.
// The scope of the auth token comes from the resource token.
$jwk = $agent->signer()->publicJwk(KEY_ID);
$authorization = $agent->requestAuthorization(
resourceToken($agentId, thumbprint($jwk)),
'suppliers:read',
agentToken: agentToken($agentId, $issuer, $jwk),
);
if (!isset($authorization['auth_token'])) {
exit("A person must approve first. See \"Before you start\".\n");
}
echo "auth token: {$authorization['token_type']}, valid for {$authorization['expires_in']} seconds\n";
// 4. The agent signs one request: the method, the address, the digest of the
// body and the Authorization header.
$url = "$resourceId/v1/suppliers/search";
$body = json(['name' => 'Northwind Labs']);
$bearer = "Bearer {$authorization['auth_token']}";
$headers = ['Authorization' => $bearer] + $agent->signer()->sign('POST', $url, $body, authorization: $bearer);
preg_match('/\(([^)]*)\)/', $headers['Signature-Input'], $covered);
echo 'signed: ' . str_replace('"', '', $covered[1]) . "\n";
echo 'request as signed: ' . verifyRequest('POST', $url, $headers, $body) . "\n";
// 6. Somebody changes the body on the way. The signature still covers the
// old digest, so the resource refuses the request.
$changed = str_replace('Northwind Labs', 'Northwind Labz', $body);
echo 'request after a change: ' . verifyRequest('POST', $url, $headers, $changed) . "\n";
php agents/aauth-signed-requests/php/aauth.php
// An agent gets an AAuth token for one API and signs a request with its own
// key. The API, which AAuth calls the resource, verifies the token and the
// signature. One program plays both parts, so that you can read the whole
// exchange in one file.
//
// java -cp "java/lib/*" agents/aauth-signed-requests/java/SignedRequests.java
import com.fasterxml.jackson.databind.ObjectMapper;
import io.lumoauth.aauth.AAuthClaims;
import io.lumoauth.aauth.AAuthClient;
import io.lumoauth.aauth.AAuthKeys;
import io.lumoauth.aauth.AAuthSigner;
import io.lumoauth.aauth.AAuthTokenResponse;
import io.lumoauth.aauth.AAuthVerifier;
import io.lumoauth.aauth.IncomingRequest;
import io.lumoauth.aauth.SignOptions;
import io.lumoauth.aauth.VerifyOptions;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.Signature;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;
public class SignedRequests {
static final String AGENT = env("AAUTH_AGENT", "https://supplier-lookup.example.com");
static final String RESOURCE = env("AAUTH_RESOURCE", "https://suppliers.example.com");
static final String KEY_ID = "key-1";
static final ObjectMapper JSON = new ObjectMapper();
public static void main(String[] args) throws Exception {
// Reads LUMOAUTH_URL and LUMOAUTH_ORG_ID.
AAuthClient agent = AAuthClient.builder()
.agentIdentifier(AGENT)
.privateKeyPem(System.getenv("AGENT_PRIVATE_KEY"))
.kid(KEY_ID)
.build();
// 3. The agent sends both tokens to LumoAuth in a signed request, and
// receives an auth token for this resource. The token carries its key.
// The scope of the auth token comes from the resource token.
AAuthTokenResponse authorization = agent.requestAuthToken(
resourceToken(agent.issuer(), AGENT, agent.publicJwkThumbprint()),
"suppliers:read",
agentToken(agent));
if (authorization.authorizationRequired()) {
throw new IllegalStateException("A person must approve first. See \"Before you start\".");
}
System.out.println("auth token: " + authorization.tokenType() + ", valid for " + authorization.expiresIn() + " seconds");
// 4. The agent signs one request: the method, the address, the digest
// of the body and the Authorization header.
String url = RESOURCE + "/v1/suppliers/search";
byte[] body = "{\"name\":\"Northwind Labs\"}".getBytes(StandardCharsets.UTF_8);
String bearer = "Bearer " + authorization.authToken();
Map<String, String> headers = new HashMap<>(agent.signRequest("POST", url, SignOptions.body(body).authorization(bearer)));
headers.put("Authorization", bearer);
var covered = Pattern.compile("\\(([^)]*)\\)").matcher(headers.get("Signature-Input"));
covered.find();
System.out.println("signed: " + covered.group(1).replace("\"", ""));
System.out.println("request as signed: " + verifyRequest(agent.issuer(), "POST", url, headers, body));
// 6. Somebody changes the body on the way. The signature still covers
// the old digest, so the resource refuses the request.
byte[] changed = new String(body, StandardCharsets.UTF_8).replace("Northwind Labs", "Northwind Labz").getBytes(StandardCharsets.UTF_8);
System.out.println("request after a change: " + verifyRequest(agent.issuer(), "POST", url, headers, changed));
}
// ----- The agent -----
// 1. The agent token says which key signs the requests of the agent. The
// agent signs this JWT itself, with a key of its registered key set.
static String agentToken(AAuthClient agent) throws Exception {
long now = System.currentTimeMillis() / 1000;
Map<String, Object> header = Map.of("typ", "agent+jwt", "alg", "EdDSA", "kid", KEY_ID);
Map<String, Object> claims = Map.of(
"iss", AGENT,
"sub", AGENT + "/session/main",
"aud", agent.issuer(),
"iat", now,
"exp", now + 300,
"jti", UUID.randomUUID().toString(),
"cnf", Map.of("jwk", agent.publicJwk().toMap()));
String input = segment(header) + "." + segment(claims);
Signature signer = Signature.getInstance("Ed25519");
signer.initSign(AAuthKeys.loadPrivateKey(System.getenv("AGENT_PRIVATE_KEY")));
signer.update(input.getBytes(StandardCharsets.US_ASCII));
return input + "." + Base64.getUrlEncoder().withoutPadding().encodeToString(signer.sign());
}
// ----- The resource -----
// 2. The resource asks LumoAuth for a resource token. The token names the
// agent, the key of the agent and the scope that the resource allows.
// The resource signs this request with its own key.
static String resourceToken(String issuer, String agentIdentifier, String agentKeyThumbprint) throws Exception {
String url = issuer + "/aauth/resource/token";
byte[] body = JSON.writeValueAsBytes(Map.of(
"resource", RESOURCE,
"agent", agentIdentifier,
"agent_jkt", agentKeyThumbprint,
"scope", "suppliers:read"));
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(url)).POST(HttpRequest.BodyPublishers.ofByteArray(body));
AAuthSigner.signRequest(System.getenv("RESOURCE_PRIVATE_KEY"), "POST", url, SignOptions.body(body)).forEach(request::header);
HttpResponse<String> answer = HttpClient.newHttpClient().send(request.build(), HttpResponse.BodyHandlers.ofString());
if (answer.statusCode() != 200) {
throw new IllegalStateException("The resource token was refused: " + answer.statusCode() + " " + answer.body());
}
return JSON.readTree(answer.body()).get("resource_token").asText();
}
// 5. The resource verifies a request. It checks the auth token, the
// digest of the body, and that the key of the token signed this request.
static String verifyRequest(String issuer, String method, String url, Map<String, String> headers, byte[] body) {
AAuthClaims claims;
try {
String token = headers.get("Authorization").substring("Bearer ".length());
claims = AAuthVerifier.verifyAuthToken(token, VerifyOptions.of(issuer, RESOURCE));
} catch (RuntimeException error) {
return "refused: " + error.getMessage();
}
if (!headers.get("Content-Digest").equals(AAuthSigner.contentDigestSha256(body))) {
return "refused: the body does not match its digest";
}
// The signature must cover the parts that matter, and it must be recent.
var input = Pattern.compile("^sig1=\\(([^)]*)\\);created=(\\d+);nonce=\"[^\"]+\"$").matcher(headers.get("Signature-Input"));
if (!input.matches()) {
return "refused: the signature input has an unknown form";
}
List<String> components = List.of(input.group(1).replace("\"", "").split(" "));
for (String name : List.of("@method", "@authority", "@path", "content-digest", "authorization")) {
if (!components.contains(name)) {
return "refused: the signature does not cover " + name;
}
}
if (Math.abs(System.currentTimeMillis() / 1000 - Long.parseLong(input.group(2))) > 60) {
return "refused: the signature is too old";
}
// The SDK rebuilds the text that the agent signed, from the request as
// it arrived, and checks it with the key of the token.
try {
claims.verifyProofOfPossession(new IncomingRequest(method, URI.create(url), headers, body));
} catch (RuntimeException error) {
return "refused: the signature does not fit the key of the token";
}
return "accepted, agent " + claims.agent() + ", scope " + claims.scope();
}
static String segment(Map<String, Object> value) throws Exception {
return Base64.getUrlEncoder().withoutPadding().encodeToString(JSON.writeValueAsBytes(value));
}
static String env(String name, String fallback) {
String value = System.getenv(name);
return value == null || value.isBlank() ? fallback : value;
}
}
java -cp "java/lib/*" agents/aauth-signed-requests/java/SignedRequests.java
#:package LumoAuth@1.7.0
#:property PublishAot=false
// An agent gets an AAuth token for one API and signs a request with its own
// key. The API, which AAuth calls the resource, verifies the token and the
// signature. One program plays both parts, so that you can read the whole
// exchange in one file.
//
// dotnet run agents/aauth-signed-requests/csharp/SignedRequests.cs
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using LumoAuth.AAuth;
var agentId = Environment.GetEnvironmentVariable("AAUTH_AGENT") ?? "https://supplier-lookup.example.com";
var resourceId = Environment.GetEnvironmentVariable("AAUTH_RESOURCE") ?? "https://suppliers.example.com";
const string KeyId = "key-1";
var agentKey = Environment.GetEnvironmentVariable("AGENT_PRIVATE_KEY")!;
// Reads LUMOAUTH_URL and LUMOAUTH_ORG_ID.
using var agent = new AAuthClient(new AAuthClientOptions { AgentIdentifier = agentId, PrivateKeyPem = agentKey, Kid = KeyId });
var http = new HttpClient();
string Segment(object value) => Convert.ToBase64String(JsonSerializer.SerializeToUtf8Bytes(value)).TrimEnd('=').Replace('+', '-').Replace('/', '_');
// ----- The agent -----
// 1. The agent token says which key signs the requests of the agent. The
// agent signs this JWT itself, with a key of its registered key set.
string AgentToken()
{
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var header = new Dictionary<string, object> { ["typ"] = "agent+jwt", ["alg"] = "EdDSA", ["kid"] = KeyId };
var claims = new Dictionary<string, object>
{
["iss"] = agentId,
["sub"] = $"{agentId}/session/main",
["aud"] = agent.Issuer,
["iat"] = now,
["exp"] = now + 300,
["jti"] = Guid.NewGuid().ToString(),
["cnf"] = new { jwk = agent.PublicJwk },
};
var input = $"{Segment(header)}.{Segment(claims)}";
var signature = AAuthPrivateKey.FromPem(agentKey).Sign(Encoding.ASCII.GetBytes(input));
return $"{input}.{Convert.ToBase64String(signature).TrimEnd('=').Replace('+', '-').Replace('/', '_')}";
}
// ----- The resource -----
// 2. The resource asks LumoAuth for a resource token. The token names the
// agent, the key of the agent and the scope that the resource allows.
// The resource signs this request with its own key.
async Task<string> ResourceToken(string agentIdentifier, string agentKeyThumbprint)
{
var url = $"{agent.Issuer}/aauth/resource/token";
var body = JsonSerializer.SerializeToUtf8Bytes(new { resource = resourceId, agent = agentIdentifier, agent_jkt = agentKeyThumbprint, scope = "suppliers:read" });
var headers = AAuthSigner.SignRequest(Environment.GetEnvironmentVariable("RESOURCE_PRIVATE_KEY")!, "POST", url, SignOptions.ForBody(body));
var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new ByteArrayContent(body) };
foreach (var (name, value) in headers)
{
if (!request.Headers.TryAddWithoutValidation(name, value)) request.Content.Headers.TryAddWithoutValidation(name, value);
}
var answer = await http.SendAsync(request);
var text = await answer.Content.ReadAsStringAsync();
if (!answer.IsSuccessStatusCode) throw new InvalidOperationException($"The resource token was refused: {(int)answer.StatusCode} {text}");
return JsonDocument.Parse(text).RootElement.GetProperty("resource_token").GetString()!;
}
// 5. The resource verifies a request. It checks the auth token, the digest
// of the body, and that the key of the token signed this request.
async Task<string> VerifyRequest(string method, string url, Dictionary<string, string> headers, byte[] body)
{
AAuthClaims claims;
try
{
var token = headers["Authorization"]["Bearer ".Length..];
claims = await AAuthVerifier.VerifyAuthTokenAsync(token, new VerifyOptions(agent.Issuer, resourceId));
}
catch (Exception error)
{
return $"refused: {error.Message}";
}
if (headers["Content-Digest"] != AAuthSigner.ContentDigestSha256(body)) return "refused: the body does not match its digest";
// The signature must cover the parts that matter, and it must be recent.
var input = Regex.Match(headers["Signature-Input"], "^sig1=\\(([^)]*)\\);created=(\\d+);nonce=\"[^\"]+\"$");
if (!input.Success) return "refused: the signature input has an unknown form";
var components = input.Groups[1].Value.Replace("\"", "").Split(' ');
foreach (var name in new[] { "@method", "@authority", "@path", "content-digest", "authorization" })
{
if (!components.Contains(name)) return $"refused: the signature does not cover {name}";
}
if (Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - long.Parse(input.Groups[2].Value)) > 60) return "refused: the signature is too old";
// The SDK rebuilds the text that the agent signed, from the request as it
// arrived, and checks it with the key of the token.
try
{
claims.VerifyProofOfPossession(new IncomingRequest(method, new Uri(url), headers, body));
}
catch (Exception)
{
return "refused: the signature does not fit the key of the token";
}
return $"accepted, agent {claims.Agent}, scope {claims.Scope}";
}
// ----- The exchange -----
// 3. The agent sends both tokens to LumoAuth in a signed request, and
// receives an auth token for this resource. The token carries its key.
// The scope of the auth token comes from the resource token.
var authorization = await agent.RequestAuthTokenAsync(
await ResourceToken(agentId, agent.PublicJwkThumbprint),
"suppliers:read",
AgentToken());
if (authorization.AuthorizationRequired) throw new InvalidOperationException("A person must approve first. See \"Before you start\".");
Console.WriteLine($"auth token: {authorization.TokenType}, valid for {authorization.ExpiresIn} seconds");
// 4. The agent signs one request: the method, the address, the digest of the
// body and the Authorization header.
var url = $"{resourceId}/v1/suppliers/search";
var body = Encoding.UTF8.GetBytes("{\"name\":\"Northwind Labs\"}");
var bearer = $"Bearer {authorization.AuthToken}";
var headers = agent.SignRequest("POST", url, new SignOptions { Body = body, Authorization = bearer });
headers["Authorization"] = bearer;
Console.WriteLine($"signed: {Regex.Match(headers["Signature-Input"], "\\(([^)]*)\\)").Groups[1].Value.Replace("\"", "")}");
Console.WriteLine($"request as signed: {await VerifyRequest("POST", url, headers, body)}");
// 6. Somebody changes the body on the way. The signature still covers the
// old digest, so the resource refuses the request.
var changed = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(body).Replace("Northwind Labs", "Northwind Labz"));
Console.WriteLine($"request after a change: {await VerifyRequest("POST", url, headers, changed)}");
dotnet run agents/aauth-signed-requests/csharp/SignedRequests.cs
Check the result
auth token: auth+jwt, valid for 3600 seconds
signed: @method @authority @path signature-key content-digest content-type authorization
request as signed: accepted, agent https://supplier-lookup.example.com, scope suppliers:read
request after a change: refused: the body does not match its digest
- The audit log of the organization records each auth token as
aauth.auth_token_issued. - Change the scope that the resource asks for to
suppliers:write, and run the program again. The resource does not list that scope, so LumoAuth refuses the resource token withinvalid_scope.
Limits
- AAuth is a draft protocol. LumoAuth follows the current draft, which may change.
- The check of the resource in these programs accepts a signature for 60 seconds. To refuse a captured request that is sent a second time, the resource must also store each
noncethat it has seen. - The SDKs sign requests, but they do not create the agent token. Each program signs that JWT itself. LumoAuth can also issue agent tokens to delegates of the agent: see
POST /aauth/agent/issuein the AAuth reference. - The Python and PHP SDKs have no check for auth tokens. The Python program checks the token with PyJWT. The PHP program asks LumoAuth, through
POST /aauth/auth/token/verify, which also reports a revoked token.