Skip to main content

Authenticate a client with a key

Replace the client secret with a signed assertion. The client keeps a private key and registers the public one.

RecipeReadyView source
Works with
JavaScript / TypeScriptPythonGoPlain HTTP

What it shows​

  1. The setup script creates a key pair for the application "Payroll export". You register the public key on the application, inline.
  2. For each token request, the application signs a client assertion. It is valid for 60 seconds and works once.
  3. LumoAuth verifies the assertion with the registered key and answers with a token. No secret is sent.
  4. A copy of the assertion, an assertion for another audience, and an assertion of another key are refused.

This recipe is for an application. For an agent of the agent registry, see An agent that signs in with a key.

Before you start​

  • An API key for the setup script, with the scopes admin:permissions:read, admin:permissions:write, admin:clients:read and admin:clients:write.
  • A confidential application with the client credentials grant. The setup script creates the application "Payroll export" and the scope payroll:read.
  • The public key registered on the application. The Admin API cannot set the key or the method, so use the portal:
    1. Open Applications & developer tools, Applications, and select Payroll export.
    2. Open the Security tab.
    3. Under FAPI 2.0 and client authentication, set Client authentication method to Private key JWT (private_key_jwt).
    4. Paste the line {"keys":[…]} that the setup script printed into Or inline JWKS (JSON).
    5. Select Save FAPI settings.
VariableValue
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
LUMOAUTH_API_KEYFor the setup script only: an API key with the scopes admin:permissions:read, admin:permissions:write, admin:clients:read and admin:clients:write. The application itself needs no API key.
CLIENT_KEY_FILEFor the setup script only, and optional: the file that holds the private key. Default: payroll-export-key.pem in your home folder.
CLIENT_IDThe client ID of the application. The setup script prints it.
CLIENT_PRIVATE_KEYThe private key of the application, as PEM text. The setup script prints a line that reads it from the key file.
CLIENT_KEY_IDThe ID (kid) of the registered public key. The setup script prints it.

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/private-key-jwt/setup.mjs
setup.mjs
// Creates what the recipe needs: the scope of the payroll API, a key pair,
// and the confidential application "Payroll export". Run it again at any
// time: it keeps the key file and the application that exist.
//
// node oauth/private-key-jwt/setup.mjs
//
// The private key is written to the file that CLIENT_KEY_FILE names. Without
// that variable, the file is payroll-export-key.pem in your home folder.
// The API key needs the scopes admin:permissions:read, admin:permissions:write,
// 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(), 'payroll-export-key.pem');

// An RSA key, so that the curl version can sign with openssl. EC and Ed25519
// keys work as well.
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. LumoAuth stores only this half. The
// key ID is the thumbprint of the key (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: 'RS256', use: 'sig' }] };

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

// The application is created with a secret, as every confidential
// application is. Once the key is set in the portal, the secret is refused.
const client = await ensure('/admin/clients', (c) => c.name === 'Payroll export', {
name: 'Payroll export',
isConfidential: true,
grantTypes: ['client_credentials'],
scopes: ['payroll:read'],
});

console.log('The application "Payroll export" is ready. In the portal, set its client authentication');
console.log('method to "Private key JWT (private_key_jwt)", and paste this line as its inline JWKS:\n');
console.log(JSON.stringify(jwks));
printEnv({
CLIENT_ID: client.clientId,
CLIENT_KEY_ID: kid,
CLIENT_PRIVATE_KEY: `$(cat '${keyFile}')`,
});

The line for CLIENT_PRIVATE_KEY reads the key file when your shell runs it. In production, keep the private key in a secrets manager.

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 curl version signs the assertion with openssl and prints the answers of the server. It leaves out the assertion of another key.

oauth/private-key-jwt/js/assertion.mjs
// An application asks for a token with a signed assertion in place of its
// client secret. Then it shows assertions that LumoAuth refuses.
//
// node oauth/private-key-jwt/js/assertion.mjs
import { CLIENT_ASSERTION_TYPE, ClientAssertionSigner, issuerFor } from '@lumoauth/agent';

const issuer = issuerFor(process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev', process.env.LUMOAUTH_ORG_ID);
const clientId = process.env.CLIENT_ID;

// The signer holds the private key. The key ID tells LumoAuth which of the
// registered public keys verifies the signature.
const signer = ClientAssertionSigner.fromPem(process.env.CLIENT_PRIVATE_KEY, { keyId: process.env.CLIENT_KEY_ID });
console.log(`key: ${signer.algorithm}, kid ${signer.keyId}`);

// The client credentials grant, with the assertion in place of the secret.
// The JS packages have this call for agents only, so it is a plain POST.
const tokenRequest = (assertion) =>
fetch(`${issuer}/oauth/token`, {
method: 'POST',
body: new URLSearchParams({
grant_type: 'client_credentials',
client_id: clientId,
client_assertion_type: CLIENT_ASSERTION_TYPE,
client_assertion: assertion,
scope: 'payroll:read',
}),
});
const status = async (response) => `${response.status}${response.ok ? '' : ` ${(await response.json()).error}`}`;

// 1. A new assertion for each request: iss and sub are the client ID, aud is
// the issuer, and it is valid for 60 seconds.
const assertion = signer.create(clientId, issuer);
const first = await tokenRequest(assertion);
const token = await first.json();
console.log(`token: ${token.token_type}, scope ${token.scope}, no secret sent`);

// 2. An assertion works once. A copy of it is refused.
console.log(`the same assertion again: ${await status(await tokenRequest(assertion))}`);

// 3. The audience is the issuer alone. An assertion for the address of the
// token endpoint is refused, so it cannot be replayed at another server.
console.log(`an assertion for the token endpoint: ${await status(await tokenRequest(signer.create(clientId, `${issuer}/oauth/token`)))}`);

// 4. A key that is not registered for the application is refused.
const other = ClientAssertionSigner.generate('RS256', process.env.CLIENT_KEY_ID);
console.log(`an assertion signed with another key: ${await status(await tokenRequest(other.create(clientId, issuer)))}`);
node oauth/private-key-jwt/js/assertion.mjs

The SDKs sign the assertions. The token request is a plain POST: the JavaScript packages have the call for agents only, and the Go call needs a client that already holds a credential. Python uses auth.client_credentials() with client_assertion.

Check the result​

Output
key: RS256, kid xwgnmz4sX0gr33u2J7nArrhdzg_xad_uQDvEycnGIHk
token: Bearer, scope payroll:read, no secret sent
the same assertion again: 401 invalid_client
an assertion for the token endpoint: 401 invalid_client
an assertion signed with another key: 401 invalid_client
  • LumoAuth answers every refusal with the same 401 invalid_client, so the answer does not tell a caller which check failed.
  • The audience of an assertion must be the issuer of the organization, alone: the issuer value of the discovery document. The address of the token endpoint is refused.
  • Once the method is Private key JWT, the client secret of the application no longer works.

Limits​

  • An inline key set is fine for a test. For production, publish the keys at a public https address and enter it as JWKS URI, so that you can rotate keys without the portal.
  • An assertion may be valid for 10 minutes at most. Sign a new one for each request.
  • A key set holds 1 to 10 keys. Each key needs a kid when the set holds more than one.
  • The method protects the token request. The access token is still a bearer token: Bind tokens to a key with DPoP adds a key to it.