11.5. Serve federation endpoints in your application
Feature guides · Example context
eduGAIN enrolls SWAMID and InCommon. SWAMID enrolls Umeå University, which enrolls its OP; InCommon enrolls the LIGO Wiki RP. The TypeScript blocks below build that hierarchy and its HTTP adapters.
Put the TypeScript blocks in one module in the order shown. Copy the software crypto helpers and adjust the import path to match your project. The examples use temporary keys and in-memory stores. See the storage guide for deployment requirements.
For a working Express integration with node-oidc-provider, read the E2E OP participant and launcher. Those are test applications with test accounts and interactions.
Install
# Trust Anchor or Intermediate
pnpm add @oidfed/authority
# Leaf OP or RP with OIDC federation roles
pnpm add @oidfed/leaf @oidfed/oidc
# The examples also import core trust helpers and the crypto adapter directly
pnpm add @oidfed/core @oidfed/crypto
# Express HTTP adapter used below
pnpm add express
pnpm add -D @types/express
The federation hierarchy in this example is:
https://edugain.example
+-- https://swamid.example
| +-- https://umu.example
| +-- https://op.umu.example
+-- https://incommon.example
+-- https://wiki.ligo.example
Each identifier needs its own HTTPS endpoint. An OP and RP share federation membership here; neither is the other's superior authority.
1. Create the Trust Anchor
import { generateSoftwareKey, softwareCrypto } from "../examples/software-crypto.js";
import { Intermediate, TrustAnchor } from "@oidfed/authority";
import { createTrustAnchorSet, MemoryFederationStorage } from "@oidfed/core";
const taKeys = await generateSoftwareKey("ES256");
const ta = await TrustAnchor.create({
entityId: "https://edugain.example",
crypto: softwareCrypto(taKeys.privateKey),
storage: new MemoryFederationStorage({ namespace: "https://edugain.example" }),
metadata: {
federation_entity: {
federation_fetch_endpoint: "https://edugain.example/fetch",
federation_list_endpoint: "https://edugain.example/list",
},
},
});
const trustAnchors = createTrustAnchorSet([
{ entityId: ta.entityId, jwks: { keys: [taKeys.publicKey] } },
]);
This example anchor has no Superiors and omits authorityHints. An anchor participating as an Intermediate in another federation can publish its own Superior hints. Pin its public federation keys through your own trusted configuration process. Learning keys from the same untrusted endpoint you are evaluating does not establish that trust.
2. Create and enroll the Intermediates
async function enrollIntermediate(id: string, superior: TrustAnchor | Intermediate) {
const signingKeys = await generateSoftwareKey("ES256");
const host = await Intermediate.create({
entityId: id, authorityHints: [superior.entityId], trustAnchors,
crypto: softwareCrypto(signingKeys.privateKey),
storage: new MemoryFederationStorage({ namespace: id }),
metadata: { federation_entity: {
federation_fetch_endpoint: `${id}/fetch`, federation_list_endpoint: `${id}/list`,
} },
});
await superior.registerSubordinate({
entityId: host.entityId, jwks: { keys: [signingKeys.publicKey] },
entityTypes: ["federation_entity"], isIntermediate: true,
});
return host;
}
const swamid = await enrollIntermediate("https://swamid.example", ta);
const umu = await enrollIntermediate("https://umu.example", swamid);
const inCommon = await enrollIntermediate("https://incommon.example", ta);
Each authority advertises Fetch and Listing and enrolls only its Immediate Subordinates. registerSubordinate() validates publication claims and coordinates lifecycle writes. Direct repository writes are for adapter integrations and must preserve those contracts independently.
3. Add the OP's federation role
Use a Leaf when the OP does not issue Subordinate Statements. An OP that is also an authority can instead compose the role into an Intermediate with the required fetch and list metadata.
import { Leaf } from "@oidfed/leaf";
import { OidcProviderRole, OidcRelyingPartyRole } from "@oidfed/oidc";
const opFederationKeys = await generateSoftwareKey("ES256");
const opProtocolKeys = await generateSoftwareKey("RS256");
const registeredClients = new Map<string, Record<string, unknown>>();
const opRole = new OidcProviderRole({
trustAnchors,
metadata: {
issuer: "https://op.umu.example",
authorization_endpoint: "https://op.umu.example/auth",
token_endpoint: "https://op.umu.example/token",
response_types_supported: ["code"],
subject_types_supported: ["public"],
id_token_signing_alg_values_supported: ["RS256"],
client_registration_types_supported: ["automatic", "explicit"],
jwks: { keys: [opProtocolKeys.publicKey] },
},
onRegistration: async (clientId, metadata) => {
registeredClients.set(clientId, metadata);
},
});
const op = await Leaf.create({
storage: new MemoryFederationStorage({ namespace: "https://op.umu.example", capabilities: ["replay"] }),
entityId: "https://op.umu.example",
authorityHints: [umu.entityId],
trustAnchors,
crypto: softwareCrypto(opFederationKeys.privateKey),
metadata: { federation_entity: { organization_name: "Example OP" } },
roles: [opRole],
});
await umu.registerSubordinate({
entityId: op.entityId,
jwks: { keys: [opFederationKeys.publicKey] },
entityTypes: ["openid_provider"],
});
Leaf.handleRequest() serves the Entity Configuration and dispatches explicit registration to the role's /registration handler. The role publishes that URL as federation_registration_endpoint.
Connect onRegistration to the client store your OP actually reads, including protocol-key metadata and registration expiry. The map above only demonstrates that handoff. Configure the OP to use the same protocol keys it publishes here; generating this metadata does not configure its token signer. Effective OP metadata must include RS256 in id_token_signing_alg_values_supported, so this example generates an RSA protocol key and advertises that algorithm.
For automatic registration, your authorization endpoint calls opRole.processAutomaticRegistration(requestObjectJwt, options) before continuing the OIDC request. On success, use the returned rpEntityId, resolvedRpMetadata, and trustChain to provision the client and bound its lifetime. Reject a failed result. A shared atomic ReplayStore is required for this method in a multi-process deployment.
If the OP supports request_uri or PAR, integrate Request Object retrieval and PAR processing into those endpoints too. The E2E OP participant shows the application wiring for the supported delivery modes.
4. Add the RP's federation role
const rpFederationKeys = await generateSoftwareKey("ES256");
const rpProtocolKeys = await generateSoftwareKey("ES256");
const rpRole = new OidcRelyingPartyRole({
signing: {requestObject:"request_object", clientAssertion:"client_assertion"},
metadata: {
redirect_uris: ["https://wiki.ligo.example/callback"],
response_types: ["code"],
grant_types: ["authorization_code"],
client_registration_types: ["automatic", "explicit"],
token_endpoint_auth_method: "private_key_jwt",
},
});
const rp = await Leaf.create({
entityId: "https://wiki.ligo.example",
authorityHints: [inCommon.entityId],
trustAnchors,
crypto: softwareCrypto(rpFederationKeys.privateKey, rpProtocolKeys.privateKey),
metadata: { federation_entity: { organization_name: "Example RP" } },
roles: [rpRole],
});
await inCommon.registerSubordinate({
entityId: rp.entityId,
jwks: { keys: [rpFederationKeys.publicKey] },
entityTypes: ["openid_relying_party"],
});
At login, call rpRole.automaticallyRegister() with the OP Entity Identifier, registered redirect URI, scope, and fresh state/nonce bound to the browser session. Handle its Result, then narrow the returned delivery field before using mode-specific fields such as authorizationUrl or formParams. See OIDC roles.
For explicit registration, call rpRole.explicitlyRegister(op.entityId, { trustAnchors }). Persist a successful result's clientId, any clientSecret, and trustChainExpiresAt. Use your OIDC client to construct the authorization request and re-register before the chain expires.
During token exchange, the HTTP destination is the validated token endpoint. A private_key_jwt assertion's audience is the validated OP Entity Identifier:
const clientAssertion = await rpRole.createClientAssertion(op.entityId);
Your OIDC client must validate session state, use the applicable PKCE/nonce protections, handle token-endpoint errors, and validate the ID Token before creating a session. Federation registration supplies trusted metadata and client credentials; these OIDC responsibilities remain in the application.
5. Adapt the Web API handler to Express
This Express 5 adapter buffers the original request bytes with a 64 KiB limit. Mount it before other body parsers and only on federation routes. It builds URLs from the configured public Entity Identifier.
import express from "express";
function federationApp(
publicEntityId: string,
handler: (request: Request) => Promise<Response>,
paths: string[],
) {
const app = express();
const readFederationBody = express.raw({ type: () => true, limit: "64kb" });
for (const path of paths) {
app.all(path, readFederationBody, async (req, res) => {
const url = new URL(req.originalUrl, publicEntityId);
if (url.origin !== new URL(publicEntityId).origin) {
res.status(400).end();
return;
}
const headers = new Headers();
for (const [name, value] of Object.entries(req.headers)) {
if (Array.isArray(value)) {
for (const item of value) headers.append(name, item);
} else if (value !== undefined) {
headers.set(name, value);
}
}
const body = req.method !== "GET" && req.method !== "HEAD" && Buffer.isBuffer(req.body)
? new Uint8Array(req.body).buffer
: undefined;
const response = await handler(new Request(url, {
method: req.method,
headers,
...(body !== undefined ? { body } : {}),
}));
res.status(response.status);
response.headers.forEach((value, name) => res.setHeader(name, value));
res.end(await response.text());
});
}
return app;
}
const taApp = federationApp(ta.entityId, (request) => ta.handleRequest(request), [
"/.well-known/openid-federation", "/fetch", "/list",
]);
const opFederationApp = federationApp(op.entityId, (request) => op.handleRequest(request), [
"/.well-known/openid-federation", "/registration",
]);
Serve each app on its configured HTTPS origin, directly or through a TLS reverse proxy. Mount SWAMID, the university, InCommon, and the RP handlers on their respective origins in the same way. In the OP application, mount the federation routes alongside the existing authorization/token routes. Forward exact JWT response content types, status codes, and bodies. The raw-body parser is attached only to the selected federation routes, so it does not consume bodies intended for the OP's authorization or token handlers.
Registration flow
- The RP fetches the OP's Entity Configuration, follows authority hints, and obtains Subordinate Statements.
- Discovery validates the chain against configured trust anchors, checks constraints, and applies metadata policies.
- Automatic registration signs a protocol Request Object and delivers it through the selected mode. The OP validates it and the RP's chain, claims its replay identifier, and provisions the client.
- Explicit registration instead posts a federation-signed Entity Configuration and receives a signed registration response. Supplied chains are validated before live discovery is attempted.
- The existing OP and RP complete the authorization code flow using the trusted metadata and credentials. Registration lifetime is bounded by trust-chain validity.