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.
What it shows
- The setup script creates a key pair for the application "Payroll export". You register the public key on the application, inline.
- For each token request, the application signs a client assertion. It is valid for 60 seconds and works once.
- LumoAuth verifies the assertion with the registered key and answers with a token. No secret is sent.
- 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:readandadmin: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:
- Open Applications & developer tools, Applications, and select Payroll export.
- Open the Security tab.
- Under 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). - Select Save FAPI settings.
| 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:permissions:read, admin:permissions:write, 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: payroll-export-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. |
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.
- Node.js
- Python
- Go
- curl
// 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
"""An application asks for a token with a signed assertion in place of its
client secret. Then it shows assertions that LumoAuth refuses.
python oauth/private-key-jwt/python/assertion.py
"""
import os
from lumoauth import ClientAssertionSigner, LumoAuth, LumoAuthApiError
lumo = LumoAuth() # reads LUMOAUTH_URL and LUMOAUTH_ORG_ID
client_id = os.environ["CLIENT_ID"]
# The signer holds the private key. The key ID tells LumoAuth which of the
# registered public keys verifies the signature.
signer = ClientAssertionSigner.from_pem(os.environ["CLIENT_PRIVATE_KEY"], key_id=os.environ["CLIENT_KEY_ID"])
print(f"key: {signer.alg}, kid {signer.key_id}")
def token_request(assertion):
"""The client credentials grant, with the assertion in place of the secret."""
try:
return lumo.auth.client_credentials(client_id, scopes=["payroll:read"], client_assertion=assertion)
except LumoAuthApiError as error:
return error
def status(answer):
return "200" if isinstance(answer, dict) else f"{answer.status_code} {answer.code}"
# 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.
assertion = signer.create(client_id, lumo.issuer)
token = token_request(assertion)
print(f"token: {token['token_type']}, scope {token['scope']}, no secret sent")
# 2. An assertion works once. A copy of it is refused.
print(f"the same assertion again: {status(token_request(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.
print(f"an assertion for the token endpoint: {status(token_request(signer.create(client_id, lumo.issuer + '/oauth/token')))}")
# 4. A key that is not registered for the application is refused.
other = ClientAssertionSigner.generate("RS256", key_id=os.environ["CLIENT_KEY_ID"])
print(f"an assertion signed with another key: {status(token_request(other.create(client_id, lumo.issuer)))}")
python oauth/private-key-jwt/python/assertion.py
// An application asks for a token with a signed assertion in place of its
// client secret. Then it shows assertions that LumoAuth refuses.
//
// go run ./oauth/private-key-jwt/go
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
issuer := lumoauth.IssuerFor(os.Getenv("LUMOAUTH_URL"), os.Getenv("LUMOAUTH_ORG_ID"))
clientID := os.Getenv("CLIENT_ID")
// The signer holds the private key. The key ID tells LumoAuth which of
// the registered public keys verifies the signature.
signer, err := lumoauth.LoadClientAssertionSigner(os.Getenv("CLIENT_PRIVATE_KEY"), lumoauth.ClientAssertionOptions{KeyID: os.Getenv("CLIENT_KEY_ID")})
if err != nil {
log.Fatal(err)
}
fmt.Printf("key: %s, kid %s\n", signer.Algorithm(), signer.KeyID())
// The client credentials grant, with the assertion in place of the
// secret. The SDK has the call on a client that holds an API key, a
// token or a secret; this application holds a key only, so it is a
// plain POST.
tokenRequest := func(assertion string) (int, map[string]any) {
response, err := http.PostForm(issuer+"/oauth/token", url.Values{
"grant_type": {"client_credentials"},
"client_id": {clientID},
"client_assertion_type": {lumoauth.ClientAssertionType},
"client_assertion": {assertion},
"scope": {"payroll:read"},
})
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
var body map[string]any
json.NewDecoder(response.Body).Decode(&body)
return response.StatusCode, body
}
status := func(assertion string) string {
code, body := tokenRequest(assertion)
if code == http.StatusOK {
return "200"
}
return fmt.Sprintf("%d %v", code, body["error"])
}
sign := func(signer *lumoauth.ClientAssertionSigner, audience string) string {
assertion, err := signer.Assertion(clientID, audience)
if err != nil {
log.Fatal(err)
}
return assertion
}
// 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.
assertion := sign(signer, issuer)
code, token := tokenRequest(assertion)
if code != http.StatusOK {
log.Fatalf("The token request failed: %d %v", code, token["error_description"])
}
fmt.Printf("token: %v, scope %v, no secret sent\n", token["token_type"], token["scope"])
// 2. An assertion works once. A copy of it is refused.
fmt.Printf("the same assertion again: %s\n", status(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.
fmt.Printf("an assertion for the token endpoint: %s\n", status(sign(signer, issuer+"/oauth/token")))
// 4. A key that is not registered for the application is refused.
other, err := lumoauth.GenerateClientAssertionSigner("RS256", os.Getenv("CLIENT_KEY_ID"))
if err != nil {
log.Fatal(err)
}
fmt.Printf("an assertion signed with another key: %s\n", status(sign(other, issuer)))
}
go run ./oauth/private-key-jwt/go
#!/bin/sh
# An application asks for a token with a signed assertion in place of its
# client secret, with curl and openssl. Then it sends the assertion again.
#
# sh oauth/private-key-jwt/http/assertion.sh
#
# The script needs curl, openssl and jq.
set -eu
ISSUER="$LUMOAUTH_URL/orgs/$LUMOAUTH_ORG_ID/api/v1"
# openssl reads the key from a file. The file is removed at the end.
KEY_FILE=$(mktemp)
trap 'rm -f "$KEY_FILE"' EXIT
printf '%s\n' "$CLIENT_PRIVATE_KEY" > "$KEY_FILE"
b64url() { openssl base64 -A | tr '+/' '-_' | tr -d '='; }
# A JWT signed with RS256: iss and sub are the client ID, aud is the issuer
# (or the address given), it is valid for 60 seconds, and its jti is new.
assertion() {
NOW=$(date +%s)
HEADER=$(printf '{"alg":"RS256","kid":"%s","typ":"client-authentication+jwt"}' "$CLIENT_KEY_ID" | b64url)
PAYLOAD=$(printf '{"iss":"%s","sub":"%s","aud":"%s","iat":%s,"exp":%s,"jti":"%s"}' \
"$CLIENT_ID" "$CLIENT_ID" "$1" "$NOW" "$((NOW + 60))" "$(openssl rand -hex 16)" | b64url)
SIGNATURE=$(printf '%s.%s' "$HEADER" "$PAYLOAD" | openssl dgst -sha256 -sign "$KEY_FILE" | b64url)
printf '%s.%s.%s' "$HEADER" "$PAYLOAD" "$SIGNATURE"
}
token_request() {
curl --silent --show-error "$ISSUER/oauth/token" \
--data "grant_type=client_credentials" \
--data "client_id=$CLIENT_ID" \
--data "client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer" \
--data "client_assertion=$1" \
--data "scope=payroll:read" \
--write-out ' HTTP %{http_code}\n'
}
# 1. The assertion takes the place of the client secret.
ASSERTION=$(assertion "$ISSUER")
token_request "$ASSERTION" | sed 's/"access_token":"[^"]*"/"access_token":"…"/'
# 2. The same assertion again: refused.
token_request "$ASSERTION"
# 3. An assertion for the address of the token endpoint: refused.
token_request "$(assertion "$ISSUER/oauth/token")"
sh oauth/private-key-jwt/http/assertion.sh
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
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
issuervalue 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
httpsaddress 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
kidwhen 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.