mTLS with Keycloak: replace client secrets and make stolen tokens useless

In short
  • Machine clients authenticate to Keycloak with an X.509 certificate instead of a client secret. The private key never leaves the client.
  • Keycloak binds every access token to that certificate (RFC 8705), and an API that checks the binding rejects a stolen token.
  • No extension needed: it's all built into Keycloak 26.4. Tested end to end, including the attacks.

Why replace client secrets?

A client secret is a shared string. It ends up in config files, CI logs and chat messages, and anyone who copies it can get tokens. Worse, a stolen access token works from anywhere until it expires.

With mutual TLS, the client proves who it is with a certificate whose private key never leaves the machine. Keycloak records the certificate's thumbprint inside the token, so the token only works on a connection that presents the same certificate.

Client secretCertificate (mTLS)
A shared string that can be copied from config, logs or CIThe private key never leaves the client
Leaked secret: anyone can get tokensA token alone is useless: the API demands the matching certificate
Rotation means touching every copyShort-lived certs from your PKI rotate automatically

This guide follows on from adding custom claims to Keycloak tokens. It suits service-to-service APIs, open banking and FAPI, and any "get rid of client secrets" project.

Step 1: Certificates

For the demo, a small PKI: a certificate authority Keycloak will trust, Keycloak's own HTTPS certificate, one certificate per machine client, and an impostor from a CA nobody trusts. In production, use your real PKI (internal CA, cert-manager, Vault, a cloud CA).

# the CA Keycloak trusts for client certificates
openssl req -x509 -newkey rsa:3072 -nodes -days 365 -subj "/CN=AIS Demo CA" -keyout ca.key -out ca.crt

# one certificate per machine client: the CN is the client's identity
for name in billing-service reporting-service; do
  openssl req -newkey rsa:2048 -nodes -subj "/CN=$name/O=Acme" -keyout $name.key -out $name.csr
  openssl x509 -req -in $name.csr -CA ca.crt -CAkey ca.key -CAcreateserial -days 365 -out $name.crt \
    -extfile <(printf "extendedKeyUsage=clientAuth")
done

# the truststore Keycloak uses to verify client certificates
keytool -importcert -noprompt -alias ais-demo-ca -file ca.crt -keystore truststore.p12 -storetype PKCS12 -storepass changeit

Client certificates need extendedKeyUsage=clientAuth.

Step 2: Run Keycloak with HTTPS and client certificates

docker network create kc-mtls
docker run -d --name keycloak --network kc-mtls -p 9443:8443 -v ./certs:/certs \
  -e KC_BOOTSTRAP_ADMIN_USERNAME=admin -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \
  -e KC_HTTPS_CERTIFICATE_FILE=/certs/keycloak.crt -e KC_HTTPS_CERTIFICATE_KEY_FILE=/certs/keycloak.key \
  -e KC_HTTPS_TRUST_STORE_FILE=/certs/truststore.p12 -e KC_HTTPS_TRUST_STORE_PASSWORD=changeit \
  -e KC_HTTPS_CLIENT_AUTH=request -e KC_HOSTNAME=https://localhost:9443 \
  quay.io/keycloak/keycloak:26.4.0 start-dev

KC_HTTPS_CLIENT_AUTH=request asks every caller for a certificate but still lets browsers and secret-based clients in. required would lock everyone else out, so only use it on a hostname that serves machine clients alone.

Step 3: Clients that use certificates, not secrets

kcadm create clients -r acme -s clientId=billing-service -s publicClient=false -s serviceAccountsEnabled=true \
  -s standardFlowEnabled=false -s directAccessGrantsEnabled=false \
  -s clientAuthenticatorType=client-x509 \
  -s 'attributes."x509.subjectdn"=(.*, )?CN=billing-service(, .*)?' \
  -s 'attributes."x509.allow.regex.pattern.comparison"=true' \
  -s 'attributes."tls.client.certificate.bound.access.tokens"=true'
  • client-x509: no client secret at all. The certificate is the credential.
  • tls.client.certificate.bound.access.tokens: every token records the thumbprint of the certificate that requested it.

The gotcha that cost us a few minutes: Keycloak formats the certificate subject in reverse order, as O=Acme, CN=billing-service. A pattern like CN=billing-service,.* never matches, and every login fails with invalid_client. Match the CN anywhere: (.*, )?CN=billing-service(, .*)?.

In the admin console, the same settings are on the client's Credentials tab (Client Authenticator: X509 Certificate, plus the Subject DN) and the Advanced tab (OAuth 2.0 Mutual TLS Certificate Bound Access Tokens Enabled). No restart needed.

Step 4: Get a certificate-bound token

Without a certificate, there's nothing to fall back on:

curl -s --cacert certs/ca.crt https://localhost:9443/realms/acme/protocol/openid-connect/token \
  -d grant_type=client_credentials -d client_id=billing-service
{"error":"invalid_client","error_description":"Invalid client or Invalid client credentials"}

With billing-service's certificate, we get a token. Decode it and there's a cnf claim:

curl -s --cacert certs/ca.crt --cert certs/billing-service.crt --key certs/billing-service.key \
  https://localhost:9443/realms/acme/protocol/openid-connect/token \
  -d grant_type=client_credentials -d client_id=billing-service | jq -r .access_token > token.txt
cut -d. -f2 token.txt | basenc -d --base64url 2>/dev/null | jq '{azp, cnf}'
{
  "azp": "billing-service",
  "cnf": { "x5t#S256": "Emo2HToBZGG-XY6ioOweB2f_06PDmOLF_XAdWPxcaxM" }
}

Hash the certificate yourself and you get the same value: the token is bound to exactly this certificate.

openssl x509 -in certs/billing-service.crt -outform DER | openssl dgst -sha256 -binary | basenc --base64url | tr -d '='
Emo2HToBZGG-XY6ioOweB2f_06PDmOLF_XAdWPxcaxM

Step 5: Try the impostors

AttemptResult
The impostor: right name (billing-service), certificate from an untrusted CARefused in the TLS handshake (certificate unknown), before Keycloak reads the request
reporting-service's valid certificate, asking for client_id=billing-serviceinvalid_client: a valid cert for a different client can't pose as this one

Step 6: An API that enforces the binding

Certificate-bound tokens only help if the API checks them. Our orders API accepts only callers with a certificate from our CA, hashes that certificate exactly the way Keycloak did, and rejects the token if they don't match:

https.createServer({ key, cert, ca, requestCert: true, rejectUnauthorized: true }, async (req, res) => {
  const peer = req.socket.getPeerCertificate();
  const thumb = createHash("sha256").update(peer.raw).digest("base64url");
  const claims = await verify(token);              // signature, issuer, expiry
  if (claims.cnf?.["x5t#S256"] !== thumb)
    return reply(401, { error: "token is not bound to your certificate" });
  reply(200, { orders: [...] });
});

Then the real test, a stolen token:

# billing-service, with its own token and certificate
{"orders":["ORD-1001","ORD-1002"],"caller":"billing-service","client":"billing-service"}

# reporting-service steals the token and uses its own valid certificate
{"error":"token is not bound to your certificate","caller":"reporting-service"}

# the stolen token with no certificate at all
curl: (56) ... tlsv13 alert certificate required

A leaked token, on its own, gets an attacker nothing.

Before you go to production

  • Behind a proxy or load balancer? Forward the client certificate (or use TLS passthrough) and set Keycloak's X.509 lookup provider (--spi-x509cert-lookup-provider=nginx|haproxy|apache|envoy).
  • Use your real PKI, with short-lived certificates and automatic rotation. Turn on revocation checks (CRL or OCSP) if certificates are long-lived.
  • Every API checks cnf.x5t#S256, or an API gateway does it for them.
  • Keep request, not required, unless the hostname serves machine clients only.
  • One subject per client, so certificates can't be swapped between clients.

Keycloak mTLS FAQ

Do I need a Keycloak extension for mTLS?

No. X.509 client authentication and certificate-bound tokens (RFC 8705) are built into Keycloak. You configure the HTTPS truststore and two client settings.

Why does every certificate login fail with invalid_client?

Usually the Subject DN pattern. Keycloak writes the subject as O=Acme, CN=client, most specific last, so match the CN anywhere with (.*, )?CN=client(, .*)? and turn on regex comparison.

Can browser apps use this?

Not practically: browsers can't be issued and manage client certificates at scale. For browser and mobile apps, bind tokens with DPoP instead: see our DPoP guide.

Rolling out mTLS or replacing client secrets? We design and implement Keycloak certificate authentication for Australian organisations, from PKI to API gateways. Talk to us.

Talk to a Keycloak specialist

The first conversation is free.

Make an enquiry