A client for the FAPI 2.0 profile
Build a client for the strictest profile: pushed requests, key-based client authentication, sender-constrained tokens and signed responses.
What it shows
- The application "Acme Treasury" has the profile FAPI 2.0 Advanced and a registered public key.
- The server of the app signs a request object with every authorization parameter, and pushes it to the PAR endpoint with a client assertion.
- After sign-in, LumoAuth sends a signed authorization response. The app verifies the signature,
iss,audandexpbefore it uses the code. - The app redeems the code with a client assertion and a DPoP proof. The token is bound to the DPoP key and works with a proof of that key.
- A pushed request that leaves out a part of the profile is refused, and the error names the part.
Before you start
- Check that your plan includes the FAPI 2.0 profile in the plans matrix.
- An API key for the setup script, with the scopes
admin:clients:readandadmin:clients:write. - A confidential application with the authorization code grant. The setup script creates the application "Acme Treasury" and a key pair.
- The key and the profile on the application. The Admin API cannot set them, so use the portal:
- Open Applications & developer tools, Applications, and select Acme Treasury.
- Open the Security tab and go to FAPI 2.0 and client authentication.
- Set Client authentication method to Private key JWT (private_key_jwt).
- Paste the line
{"keys":[…]}that the setup script printed into Or inline JWKS (JSON). - Set Security profile to FAPI 2.0 Advanced. Require PAR and Require DPoP turn on with it.
- Select Save FAPI 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. |
LUMOAUTH_API_KEY | For the setup script only: an API key with the scopes admin:clients:read and admin:clients:write. The application itself needs no API key. |
CLIENT_KEY_FILE | For the setup script only, and optional: the file that holds the private key. Default: acme-treasury-key.pem in your home folder. |
CLIENT_ID | The client ID of the application. The setup script prints it. |
CLIENT_PRIVATE_KEY | The private key of the application, as PEM text. The setup script prints a line that reads it from the key file. |
CLIENT_KEY_ID | The ID (kid) of the registered public key. The setup script prints it. |
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 a key pair, writes the private key to a file outside the repository, and creates the application. It prints the public key set that you paste in the portal.
node oauth/fapi-2-client/setup.mjs
setup.mjs
// Creates what the recipe needs: a key pair, and the confidential application
// "Acme Treasury", a web app with a server. Run it again at any time: it
// keeps the key file and the application that exist.
//
// node oauth/fapi-2-client/setup.mjs
//
// The private key is written to the file that CLIENT_KEY_FILE names. Without
// that variable, the file is acme-treasury-key.pem in your home folder.
// The API key needs the scopes admin:clients:read and admin:clients:write.
import { createHash, createPublicKey, generateKeyPairSync } from 'node:crypto';
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { ensure, printEnv } from '../../_lib/admin.mjs';
const keyFile = process.env.CLIENT_KEY_FILE ?? join(homedir(), 'acme-treasury-key.pem');
// Where LumoAuth sends the browser after sign-in. The program listens there.
const redirectUri = process.env.REDIRECT_URI ?? 'http://localhost:3000/callback';
// The key signs the client assertions and the request objects. The DPoP key
// is another one: the program makes it at each start.
if (!existsSync(keyFile)) {
const pem = generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey.export({ type: 'pkcs8', format: 'pem' });
writeFileSync(keyFile, pem, { mode: 0o600 });
}
// The public half of the key, as a JWK. The key ID is its thumbprint (RFC 7638).
const { kty, n, e } = createPublicKey(readFileSync(keyFile, 'utf8')).export({ format: 'jwk' });
const kid = createHash('sha256').update(JSON.stringify({ e, kty, n })).digest('base64url');
const jwks = { keys: [{ kty, n, e, kid, alg: 'PS256', use: 'sig' }] };
const client = await ensure('/admin/clients', (c) => c.name === 'Acme Treasury', {
name: 'Acme Treasury',
isConfidential: true,
grantTypes: ['authorization_code'],
redirectUris: [redirectUri],
scopes: ['openid', 'profile'],
});
console.log('The application "Acme Treasury" is ready. In the portal, set its client authentication');
console.log('method to "Private key JWT (private_key_jwt)", paste this line as its inline JWKS,');
console.log('and choose the security profile "FAPI 2.0 Advanced":\n');
console.log(JSON.stringify(jwks));
printEnv({
CLIENT_ID: client.clientId,
CLIENT_KEY_ID: kid,
CLIENT_PRIVATE_KEY: `$(cat '${keyFile}')`,
REDIRECT_URI: redirectUri,
});
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. The program prints an address after the second line and waits until you have signed in there. It redeems the code at once: a code of a FAPI 2.0 application is valid for 60 seconds.
- Node.js
// A client for the FAPI 2.0 Advanced profile. It pushes a signed request
// object, authenticates with a key in place of a secret, reads a signed
// authorization response, and gets a token that is bound to a DPoP key.
//
// node oauth/fapi-2-client/js/fapi.mjs
import { constants, createPrivateKey, createPublicKey, randomUUID, sign, verify } from 'node:crypto';
import { EventEmitter, once } from 'node:events';
import http from 'node:http';
import { CLIENT_ASSERTION_TYPE, ClientAssertionSigner, DpopProofSigner, JwksCache, decodeJwt, fetchWithDpop, issuerFor } from '@lumoauth/agent';
import { generateCodeChallenge, generateCodeVerifier, generateState } from '@lumoauth/backend';
const issuer = issuerFor(process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev', process.env.LUMOAUTH_ORG_ID);
const redirectUri = process.env.REDIRECT_URI ?? 'http://localhost:3000/callback';
const { CLIENT_ID: clientId, CLIENT_KEY_ID: keyId } = process.env;
// The key of the application signs the client assertions and the request
// object, with PS256. The token is bound to a second key, the DPoP key.
const assertions = ClientAssertionSigner.fromPem(process.env.CLIENT_PRIVATE_KEY, { keyId, algorithm: 'PS256' });
const clientAuth = () => ({ client_id: clientId, client_assertion_type: CLIENT_ASSERTION_TYPE, client_assertion: assertions.create(clientId, issuer) });
const dpop = DpopProofSigner.generate();
// The SDKs have no signer for request objects, so node:crypto signs it.
const pss = { padding: constants.RSA_PKCS1_PSS_PADDING, saltLength: 32 };
const part = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');
function signRequestObject(claims) {
const input = `${part({ alg: 'PS256', kid: keyId, typ: 'oauth-authz-req+jwt' })}.${part(claims)}`;
const key = createPrivateKey(process.env.CLIENT_PRIVATE_KEY);
return `${input}.${sign('sha256', Buffer.from(input), { key, ...pss }).toString('base64url')}`;
}
// The redirect URI of the application. Each request to it answers one
// authorization request.
const callbacks = new EventEmitter();
const server = http.createServer((request, response) => {
response.end('Done. You can close this tab.');
callbacks.emit('callback', new URL(request.url, redirectUri).searchParams);
});
server.listen(new URL(redirectUri).port);
const push = (form) => fetch(`${issuer}/oauth/par`, { method: 'POST', body: new URLSearchParams({ ...clientAuth(), ...form }) });
// 1. The request object holds every authorization parameter, signed. It asks
// for a signed response (response_mode=jwt) and is valid for 5 minutes.
const codeVerifier = generateCodeVerifier();
const state = generateState();
const now = Math.floor(Date.now() / 1000);
const claims = {
iss: clientId,
aud: issuer,
nbf: now,
exp: now + 300,
jti: randomUUID(),
client_id: clientId,
response_type: 'code',
response_mode: 'jwt',
redirect_uri: redirectUri,
scope: 'openid profile',
state,
code_challenge: await generateCodeChallenge(codeVerifier),
code_challenge_method: 'S256',
};
const requestObject = signRequestObject(claims);
// 2. The server pushes it to the PAR endpoint, with a client assertion.
const pushed = await push({ request: requestObject });
if (pushed.status !== 201) throw new Error(`The pushed request failed: ${await pushed.text()}`);
const { request_uri: requestUri } = await pushed.json();
console.log(`pushed: HTTP ${pushed.status}, a signed request object and a client assertion`);
console.log(`Open this address in a browser and sign in:\n${issuer}/oauth/authorize?${new URLSearchParams({ client_id: clientId, request_uri: requestUri })}\n`);
const [callback] = await once(callbacks, 'callback');
// 3. The response is a JWT that the organization signed. Verify it with the
// published keys, then check iss, aud and exp before using the code.
const jarm = callback.get('response');
const [header, payload, signature] = jarm.split('.');
const { alg, kid } = JSON.parse(Buffer.from(header, 'base64url'));
const jwk = await new JwksCache().find(issuer, kid);
const options = alg.startsWith('PS') ? { key: createPublicKey({ key: jwk, format: 'jwk' }), ...pss } : createPublicKey({ key: jwk, format: 'jwk' });
const signed = verify('sha256', Buffer.from(`${header}.${payload}`), options, Buffer.from(signature, 'base64url'));
const response = decodeJwt(jarm).claims;
if (!signed || response.iss !== issuer || response.aud !== clientId || response.exp < Date.now() / 1000 || response.state !== state) {
throw new Error('The authorization response is not valid.');
}
console.log(`signed response: ${alg}, signature valid, iss and aud match, code received`);
// 4. The code goes to the token endpoint with a client assertion and a DPoP
// proof. The code is valid for 60 seconds.
const tokenResponse = await fetchWithDpop(fetch, `${issuer}/oauth/token`, {
method: 'POST',
body: new URLSearchParams({ ...clientAuth(), grant_type: 'authorization_code', code: response.code, redirect_uri: redirectUri, code_verifier: codeVerifier }),
}, dpop);
const tokens = await tokenResponse.json();
if (!tokenResponse.ok) throw new Error(`The token request failed: ${JSON.stringify(tokens)}`);
const bound = decodeJwt(tokens.access_token).claims.cnf?.jkt === dpop.thumbprint;
console.log(`token: ${tokens.token_type}, bound to the DPoP key: ${bound ? 'yes' : 'no'}`);
// 5. The token works with a proof of the same key, here at the UserInfo endpoint.
const userinfo = await fetchWithDpop(fetch, `${issuer}/oauth/userinfo`, { method: 'GET' }, dpop, { accessToken: tokens.access_token });
console.log(`userinfo with a DPoP proof: ${userinfo.status}`);
// 6. A pushed request that leaves out a part of the profile is refused.
const refusal = async (form) => {
const answer = await push(form);
return `${answer.status} ${(await answer.json()).error_description}`;
};
const plain = { response_type: 'code', redirect_uri: redirectUri, scope: 'openid', state, code_challenge: await generateCodeChallenge(codeVerifier), code_challenge_method: 'S256' };
console.log(`a request without a request object: ${await refusal(plain)}`);
const unsignedResponse = signRequestObject({ ...claims, jti: randomUUID(), response_mode: undefined });
console.log(`a request object without response_mode=jwt: ${await refusal({ request: unsignedResponse })}`);
server.close();
server.closeAllConnections();
node oauth/fapi-2-client/js/fapi.mjs
@lumoauth/agent signs the client assertions and the DPoP proofs, and finds the signing key of the organization. No SDK signs a request object, so the program signs it with node:crypto. It verifies the signed response the same way. The key of the application signs with PS256, as the FAPI 2.0 profile asks.
Check the result
pushed: HTTP 201, a signed request object and a client assertion
signed response: RS256, signature valid, iss and aud match, code received
token: DPoP, bound to the DPoP key: yes
userinfo with a DPoP proof: 200
a request without a request object: 400 This client must send its authorization request as a signed request object (the request parameter).
a request object without response_mode=jwt: 400 This client must ask for a signed authorization response: send response_mode=jwt (or query.jwt, fragment.jwt, form_post.jwt).
- The address that the browser opens holds
client_idandrequest_urionly. The callback holds one parameter,response. - With FAPI 2.0 Baseline in place of Advanced, the request object and the signed response are optional. The other rules stay.
- The client secret of the application no longer works at the token endpoint or the PAR endpoint. LumoAuth answers
invalid_client.
Limits
- A code of a FAPI 2.0 application is valid for 60 seconds. Redeem it as soon as the callback arrives.
- A request object of a FAPI 2.0 application needs
nbfandexp, andexpmay be at most 60 minutes afternbf. - The organization signs the response with its own key and algorithm, here RS256.
- An inline key set is fine for a test. For production, publish the keys at a public
httpsaddress and enter it as JWKS URI. - Mutual TLS is not offered, for client authentication or for binding tokens. Use a key with
private_key_jwtand DPoP. - The parts one by one: Push the authorization request, Authenticate a client with a key and Bind tokens to a key with DPoP.