Skip to content
Workload and AI agent identity · Chapter 5 of 20 Day 4: Federation without a cloud – the central badge office accepts the building badge

Day 4: Federation without a cloud – the central badge office accepts the building badge

Goal: set up Keycloak so that it trusts the cluster, and log a pod in to Keycloak with its ServiceAccount token – without a client secret · Duration: about 120 min · Prerequisite: Day 3 completed

Where we start

# on id2
curl -s --cacert ~/cluster-ca.crt https://172.16.0.126:6443/.well-known/openid-configuration

Expected:

{"issuer":"https://172.16.0.126:6443","jwks_uri":"https://172.16.0.126:6443/openid/v1/jwks","response_types_supported":["id_token"],"subject_types_supported":["public"],"id_token_signing_alg_values_supported":["RS256"]}
# on id1
sudo cat /etc/rancher/k3s/config.yaml

Expected:

disable:
  - traefik
kube-apiserver-arg:
  - service-account-extend-token-expiration=false
  - service-account-issuer=https://172.16.0.126:6443
  - service-account-issuer=https://kubernetes.default.svc.cluster.local
  - authentication-config=/etc/rancher/k3s/authn.yaml

In addition, the pods kasse and lager are running in the namespace laden, the ServiceAccounts kasse and lager-pruefer exist, and the issuer switch from Day 3 was at least an hour ago.

Introduction

Up to now only services inside the building have checked building badges: the API server itself, and on Day 3 a verifier with the specimen card. Today an office joins that has nothing to do with the cluster: Keycloak, the central badge office where people and programs log in to get to applications.

The usual way looks like this: a program gets a client in Keycloak with a client secret, and the secret sits next to the pod as a Kubernetes Secret. That is exactly the master key under the doormat from Day 1 – just with a different lock. Today you do it the way cloud providers do with “Workload Identity Federation”, only self-hosted: Keycloak trusts the cluster’s issuer. The pod presents its building badge and gets a badge from Keycloak in exchange. There is no secret.

Today you will learn:

  • how to cleanly remove the old issuer from Day 3,
  • how to install Keycloak 26.8 on a VM and run it as a service,
  • why Keycloak in development mode is at first reachable only from itself,
  • how to create a Kubernetes identity provider and a client with “Signed JWT – Federated”,
  • how to log a pod in to Keycloak with a projected token,
  • which badges Keycloak rejects – and which it surprisingly accepts.

Background

The picture for today: the badge exchange at the central badge office

Your office building does not stand alone. On the campus there is a central badge office that manages access to shared facilities for many buildings – canteen, data center, archive. Until now, every employee who wanted to go there got their own password for the central office. The password then lay in a desk drawer, and nobody knew who else knew it.

Now a new rule applies:

  • The central badge office puts up your building’s specimen card. It noted the address of your badge office once and fetches the JWKS from there. That is the identity provider of type kubernetes.
  • It keeps a list: “The building badge of system:serviceaccount:laden:kasse belongs to the account kasse.” That is the client with its federated subject.
  • The employee presents their building badge, issued for exactly this door: the address of the central badge office as audience. That is the client assertion.
  • They get a badge of the central office, valid for five minutes. That is Keycloak’s access token.
  • There is no password any more. Anyone without a genuine building badge gets no further.

The terms

Term Meaning in the picture
Keycloak identity and access management server, issues OIDC tokens central badge office
Realm self-contained area in Keycloak with its own clients, users and keys a department of the badge office
Client a program that logs in to Keycloak account on the list
Client secret password of a client master key under the doormat
Identity provider (type kubernetes) trust relationship with a cluster issuer the neighboring building’s specimen card on display
Client assertion signed token with which a client identifies itself instead of with a secret presented building badge
Signed JWT – Federated (federated-jwt) authentication method that verifies an assertion from an outside issuer badge exchange
Federated subject the sub value that belongs to a client name on the list
Client credentials grant OAuth flow in which a program logs in by itself, without a human “I am here on my own behalf”

Remember: Federation means: the central office checks the building’s badge instead of handing out its own passwords. What you protect is no longer a secret but a trust relationship.

What Keycloak checks in an assertion

Keycloak checks the same things as your offline verifier on Day 3, and a bit more:

Check against what error in the lab
Issuer iss must match an identity provider in the realm –
Client sub must be registered as federated subject on exactly one client client_not_found
Signature public key from the issuer’s JWKS invalid_client_credentials
Audience aud must be the realm’s address Invalid token audience
Time active, and iat at most 3600 seconds ago see Drill 6

One thing Keycloak explicitly does not check for Kubernetes tokens: whether the same token has been used before. A building badge is not a single-use ticket.

Drill 1: Taking down the old name

Where you are: on id1.

What you have afterwards: a cluster that only accepts tokens from its new issuer.

On Day 3 you switched the issuer and left the old name as a second entry so that existing tokens would remain valid. More than an hour has passed since then. Every token a kubelet put into a pod has been renewed in the meantime. Time to clean up.

Step 1 – create a working folder.

# on id1
mkdir -p ~/kurs/04

Step 2 – does the badge in the pod already carry the new name? The visitor pod from the Preparation uses the normal, automatically mounted token:

# on id1
kubectl exec besucher -- cat /var/run/secrets/kubernetes.io/serviceaccount/token > ~/kurs/04/besucher.jwt
# on id1
step crypto jwt inspect --insecure < ~/kurs/04/besucher.jwt

Expected (excerpt – look for aud, exp, iat and iss):

    "aud": [
      "https://kubernetes.default.svc.cluster.local",
      "k3s"
    ],
    "exp": 1796122934,
    "iat": 1796119327,
    "iss": "https://172.16.0.126:6443",

What you see: The kubelet has renewed the badge; it already carries the new issuer. The audience, on the other hand, is still the old one: k3s sets --api-audiences itself to https://kubernetes.default.svc.cluster.local,k3s, and you did not change that. Issuer and audience are two different things. Also note exp - iat: 3607 seconds. That comes back in Drill 6.

Step 3 – remove the second entry.

# on id1
sudo nano /etc/rancher/k3s/config.yaml
/etc/rancher/k3s/config.yaml new file
disable:
  - traefik
kube-apiserver-arg:
  - service-account-extend-token-expiration=false
  - service-account-issuer=https://172.16.0.126:6443
  - authentication-config=/etc/rancher/k3s/authn.yaml

The line service-account-issuer=https://kubernetes.default.svc.cluster.local is gone, nothing else.

Step 4 – restart and wait.

# on id1
sudo systemctl restart k3s
# on id1
kubectl wait --for=condition=Ready node/id1 --timeout=120s

Expected:

node/id1 condition met

Step 5 – is the current badge still valid? As on Day 3, you ask the API server who you are with a SelfSubjectReview – this time with the visitor badge:

# on id1
TOKEN=$(cat ~/kurs/04/besucher.jwt)
# on id1
curl -s --cacert ~/cluster-ca.crt -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"apiVersion":"authentication.k8s.io/v1","kind":"SelfSubjectReview"}' https://172.16.0.126:6443/apis/authentication.k8s.io/v1/selfsubjectreviews -o ~/kurs/04/wer.json
# on id1
jq -r .status.userInfo.username ~/kurs/04/wer.json

Expected:

system:serviceaccount:default:default

Step 6 – and a badge with the old name? besucher-neu.jwt from Day 2 still carries the old issuer:

# on id1
TOKEN=$(cat ~/besucher-neu.jwt)
# on id1
curl -s --cacert ~/cluster-ca.crt -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"apiVersion":"authentication.k8s.io/v1","kind":"SelfSubjectReview"}' https://172.16.0.126:6443/apis/authentication.k8s.io/v1/selfsubjectreviews

Expected (excerpt):

  "message": "Unauthorized",
  "reason": "Unauthorized",
  "code": 401

What you see: Rejected. To be honest, the API server would have rejected it even with the second entry: it has been expired since 09:25 UTC. That was exactly the condition for cleaning up. There is no valid badge with the old name any more, so no one is harmed by no longer accepting it.

Remember: You remove an old issuer only once the last token with its name has expired. With short lifetimes that takes an hour, with year-long tokens a year.

Save your progress? Sign up for free

Drill 2: Setting up the badge office

Where you are: on id1.

What you have afterwards: Keycloak 26.8.2 with a verified checksum under /opt/keycloak, run by its own system user.

Keycloak is available as a container image and as an archive. You use the archive: there is no Docker on id1, and as a plain service you see more clearly what Keycloak needs.

Step 1 – install Java. Keycloak is a Java program. The documentation for 26.8 names OpenJDK 25; Ubuntu 24.04 has the package without graphical libraries (headless):

# on id1
sudo apt-get install -y openjdk-25-jre-headless
# on id1
java -version

Expected:

openjdk version "25.0.5.1" 2026-11-17
OpenJDK Runtime Environment (build 25.0.5.1+2-1-24.04.1-Ubuntu)
OpenJDK 64-Bit Server VM (build 25.0.5.1+2-1-24.04.1-Ubuntu, mixed mode, sharing)

Step 2 – download the archive and checksum.

# on id1
cd ~/kurs/04
# on id1
curl -sLO https://github.com/keycloak/keycloak/releases/download/26.8.2/keycloak-26.8.2.tar.gz
# on id1
curl -sLO https://github.com/keycloak/keycloak/releases/download/26.8.2/keycloak-26.8.2.tar.gz.sha1
  • -s – no progress display,
  • -L – follow redirects; GitHub redirects downloads to another server,
  • -O – save under the file name from the address.
# on id1
ls -l keycloak-26.8.2.tar.gz*

Expected:

-rw-rw-r-- 1 ubuntu ubuntu 173550645 Dec  1 10:27 keycloak-26.8.2.tar.gz
-rw-rw-r-- 1 ubuntu ubuntu        40 Dec  1 10:27 keycloak-26.8.2.tar.gz.sha1

Step 3 – compare the checksum. The .sha1 file contains only the expected checksum:

# on id1
cat keycloak-26.8.2.tar.gz.sha1

Expected:

7918de2786c7db466152128bea350becbd40a58f
# on id1
sha1sum keycloak-26.8.2.tar.gz

Expected:

7918de2786c7db466152128bea350becbd40a58f  keycloak-26.8.2.tar.gz

What you see: Both values match. The archive was not damaged on the way. This does not help against an attacker who replaces the archive and the checksum on GitHub – that would require a signature. More on this in the enterprise part.

Step 4 – a dedicated user for the service. Keycloak should run neither as root nor as ubuntu:

# on id1
sudo useradd --system --home-dir /opt/keycloak --shell /usr/sbin/nologin keycloak
  • --system – system user, without an expiry date and with a low user ID,
  • --home-dir /opt/keycloak – the home directory is the installation,
  • --shell /usr/sbin/nologin – nobody can log in as this user.

Step 5 – unpack and link.

# on id1
sudo tar -xzf ~/kurs/04/keycloak-26.8.2.tar.gz -C /opt
# on id1
sudo ln -s /opt/keycloak-26.8.2 /opt/keycloak
# on id1
sudo chown -R keycloak:keycloak /opt/keycloak-26.8.2
# on id1
ls -l /opt/keycloak/

Expected:

total 40
-rw-r--r-- 1 keycloak keycloak 11358 Nov  5 15:27 LICENSE.txt
-rw-r--r-- 1 keycloak keycloak   641 Nov  5 15:27 README.md
drwxr-xr-x 3 keycloak keycloak  4096 Nov  5 15:36 bin
drwxr-xr-x 3 keycloak keycloak  4096 Dec  1 10:27 conf
drwxr-xr-x 5 keycloak keycloak  4096 Nov  5 15:36 lib
drwxr-xr-x 2 keycloak keycloak  4096 Dec  1 10:27 providers
drwxr-xr-x 2 keycloak keycloak  4096 Dec  1 10:27 themes
-rw-r--r-- 1 keycloak keycloak    26 Nov  5 15:27 version.txt

What you see: The link /opt/keycloak points to the versioned installation. For an update you unpack the new version next to it and only repoint the link.

Remember: A badge office runs under its own user and from a verified archive. Whoever takes it over can issue badges for any client.

Save your progress? Sign up for free

Drill 3: Opening the badge office

Where you are: on id1, briefly on id2 at the end.

What you have afterwards: Keycloak as a systemd service that trusts the cluster certificates and is reachable from anywhere in the lab network under a fixed address.

Step 1 – room for your own configuration. The bundled keycloak.conf contains only comments. You keep it and write a short one of your own:

# on id1
sudo mv /opt/keycloak/conf/keycloak.conf /opt/keycloak/conf/keycloak.conf.orig

Step 2 – provide the cluster CA. Keycloak will fetch the JWKS over HTTPS from https://172.16.0.126:6443. The certificate there was issued by the cluster’s CA, and Java does not know that CA. You have had the file cluster-ca.crt since Day 1:

# on id1
sudo cp ~/cluster-ca.crt /opt/keycloak/conf/cluster-ca.crt

Step 3 – the first configuration.

# on id1
sudo nano /opt/keycloak/conf/keycloak.conf
/opt/keycloak/conf/keycloak.conf new file
# Ausweisstelle des Bürogebäudes – Laborbetrieb (start-dev)
http-port=8080
truststore-paths=/opt/keycloak/conf/cluster-ca.crt
Option Value Meaning
http-port 8080 in the lab Keycloak speaks unencrypted HTTP on port 8080
truststore-paths path to the CA additional certificates Keycloak trusts for outgoing HTTPS connections
# on id1
sudo chown keycloak:keycloak /opt/keycloak/conf/keycloak.conf /opt/keycloak/conf/cluster-ca.crt
# on id1
ls -l /opt/keycloak/conf/

Expected:

total 24
-rw-r--r-- 1 keycloak keycloak  398 Nov  5 15:27 README.md
-rw-r--r-- 1 keycloak keycloak 1083 Nov  5 15:36 cache-ispn.xml
-rw-r--r-- 1 keycloak keycloak  570 Dec  1 10:33 cluster-ca.crt
-rw-r--r-- 1 keycloak keycloak  130 Dec  1 10:33 keycloak.conf
-rw-r--r-- 1 keycloak keycloak 1151 Nov  5 15:27 keycloak.conf.orig
drwxr-xr-x 2 keycloak keycloak 4096 Nov  5 15:27 truststores

Step 4 – create the first administrator. Keycloak starts without any user. The command bootstrap-admin creates a temporary administrator in the database and asks for the password twice. Think of a long password; it ends up in no file:

# on id1
sudo -u keycloak /opt/keycloak/bin/kc.sh bootstrap-admin user --username admin
  • sudo -u keycloak – as the service user, so that the database files belong to it,
  • bootstrap-admin user – create an administrator with a password,
  • --username admin – its name; without this option it would be called temp-admin.

Expected (excerpt – the lines in between are startup messages; after about a minute the command is done):

Enter password:
Enter password again:
… INFO  [org.keycloak.truststore.TruststoreBuilder] (main) Found the following truststore files in the truststore paths [/opt/keycloak/conf/cluster-ca.crt]
… INFO  [org.keycloak.services] (main) KC-SERVICES0050: Initializing master realm
… INFO  [org.keycloak.services] (main) KC-SERVICES0077: Created temporary admin user with username admin
… INFO  [io.quarkus] (main) Keycloak stopped in 1.317s

What you see: Keycloak found the cluster CA, created the database (in development mode an H2 file under /opt/keycloak/data), set up the realm master and created the administrator. “Temporary” means: Keycloak reminds you in the web interface to replace it with a real administrator.

Step 5 – Keycloak as a service.

# on id1
sudo nano /etc/systemd/system/keycloak.service
/etc/systemd/system/keycloak.service new file
[Unit]
Description=Keycloak – Ausweisstelle des Bürogebäudes (Labor)
After=network-online.target
Wants=network-online.target

[Service]
User=keycloak
Group=keycloak
ExecStart=/opt/keycloak/bin/kc.sh start-dev
Restart=on-failure

[Install]
WantedBy=multi-user.target
Option Meaning
After=/Wants=network-online.target only start once the network is up
User=/Group=keycloak run as the service user
ExecStart=… start-dev development mode: HTTP allowed, H2 database, no mandatory settings
Restart=on-failure restart after a crash
# on id1
sudo systemctl daemon-reload
# on id1
sudo systemctl enable --now keycloak

Expected:

Created symlink /etc/systemd/system/multi-user.target.wants/keycloak.service → /etc/systemd/system/keycloak.service.

Step 6 – is it open? Keycloak needs about half a minute. Look at the journal:

# on id1
sudo journalctl -u keycloak --no-pager -o cat --grep "Listening"

Repeat the command until a line appears.

Expected:

2026-12-01 10:37:39,142 INFO  [io.quarkus] (main) Keycloak 26.8.2 on JVM (powered by Quarkus 3.40.1.1) started in 28.506s. Listening on: http://localhost:8080

Read the end of the line carefully: localhost.

# on id1
curl -s http://localhost:8080/realms/master/.well-known/openid-configuration -o ~/kurs/04/master-oidc.json
# on id1
jq .issuer ~/kurs/04/master-oidc.json

Expected:

"http://localhost:8080/realms/master"

From id1 itself it works. Now the way a pod would reach Keycloak – via the VM’s address:

# on id1
curl -sS http://172.16.0.126:8080/realms/master

Expected:

curl: (7) Failed to connect to 172.16.0.126 port 8080 after 0 ms: Couldn't connect to server
# on id1
sudo ss -ltnp sport = :8080

Expected:

State  Recv-Q Send-Q      Local Address:Port Peer Address:PortProcess
LISTEN 0      4096   [::ffff:127.0.0.1]:8080            *:*    users:(("java",pid=119269,fd=246))

What you see: In development mode Keycloak 26.8 only listens on 127.0.0.1. That is a protective setting: a developer Keycloak should not accidentally be exposed on the network. For you this means: the badge office has opened, but the door only opens inward. No pod gets there.

There is a second problem in the first output: the issuer is called http://localhost:8080/.... In development mode Keycloak takes the name from the request. If a pod asks via the IP, the issuer has a different name than it has for you on id1. On Day 3 you saw why an issuer needs a fixed name – the same applies here, because in a moment the audience of the building badges will be exactly this address.

Step 7 – a door to the outside and a fixed name.

# on id1
sudo nano /opt/keycloak/conf/keycloak.conf
/opt/keycloak/conf/keycloak.conf changes in green
# Ausweisstelle des Bürogebäudes – Laborbetrieb (start-dev)
http-host=0.0.0.0
http-port=8080
hostname=http://172.16.0.126:8080
truststore-paths=/opt/keycloak/conf/cluster-ca.crt
Option Value Meaning
http-host 0.0.0.0 listen on all of the VM’s addresses
hostname http://172.16.0.126:8080 fixed public address; Keycloak derives issuer and endpoints from it, no matter how it is addressed
# on id1
sudo systemctl restart keycloak
# on id1
sudo journalctl -u keycloak --no-pager -o cat --since "-2min" --grep "Listening"

Repeat the command until a line with 0.0.0.0 appears.

Expected:

2026-12-01 10:41:36,480 INFO  [io.quarkus] (main) Keycloak 26.8.2 on JVM (powered by Quarkus 3.40.1.1) started in 28.669s. Listening on: http://0.0.0.0:8080

Step 8 – the same name from inside and outside.

# on id1
curl -s http://localhost:8080/realms/master/.well-known/openid-configuration -o ~/kurs/04/master-oidc.json
# on id1
jq .issuer ~/kurs/04/master-oidc.json

Expected:

"http://172.16.0.126:8080/realms/master"
# on id2
curl -s http://172.16.0.126:8080/realms/master/.well-known/openid-configuration -o master-oidc.json
# on id2
jq .issuer,.token_endpoint master-oidc.json

Expected:

"http://172.16.0.126:8080/realms/master"
"http://172.16.0.126:8080/realms/master/protocol/openid-connect/token"

What you see: Even though you ask localhost on id1, Keycloak now names the fixed address. And id2 – standing in for any pod – reaches Keycloak.

Remember: A badge office needs a door to the outside (http-host) and a fixed name (hostname). Without a fixed name the issuer depends on who is asking.

Save your progress? Sign up for free

Drill 4: Putting up the specimen card and creating the list

Where you are: on id1.

What you have afterwards: a realm gebaeude with an identity provider for your cluster and a client kasse that can only log in with the building badge of the ServiceAccount kasse.

You set up Keycloak with the bundled command-line tool kcadm.sh. The web interface can do the same; commands, however, can be read back and repeated.

Step 1 – log in.

# on id1
/opt/keycloak/bin/kcadm.sh config credentials --server http://localhost:8080 --realm master --user admin
Option Value Meaning
config credentials log in and save the session
--server http://localhost:8080 address of Keycloak
--realm master which realm the user lives in
--user admin the administrator from Drill 3

Expected:

Logging into http://localhost:8080 as user admin of realm master
Enter password:

After the input there is no further message. Where did kcadm.sh store the session?

# on id1
ls -l ~/.keycloak/

Expected:

total 4
-rw------- 1 ubuntu ubuntu 1905 Dec  1 10:41 kcadm.config

What you see: A file with the administrator’s access token and refresh token, readable only by you. That too is a key at the desk – short-lived, but powerful. On a shared machine you log out again afterwards.

Step 2 – a realm of your own. Keycloak uses the realm master for its own administration. Applications get a realm of their own:

# on id1
/opt/keycloak/bin/kcadm.sh create realms -s realm=gebaeude -s enabled=true

Expected:

Created new realm with id 'gebaeude'

Step 3 – can this realm exchange badges? How clients may authenticate is defined in a flow (flow) named clients:

# on id1
/opt/keycloak/bin/kcadm.sh get authentication/flows/clients/executions -r gebaeude --fields displayName,providerId,requirement

Expected:

[ {
  "requirement" : "ALTERNATIVE",
  "displayName" : "Client Id and Secret",
  "providerId" : "client-secret"
}, {
  "requirement" : "ALTERNATIVE",
  "displayName" : "Signed JWT",
  "providerId" : "client-jwt"
}, {
  "requirement" : "ALTERNATIVE",
  "displayName" : "Signed JWT with Client Secret",
  "providerId" : "client-secret-jwt"
}, {
  "requirement" : "ALTERNATIVE",
  "displayName" : "X509 Certificate",
  "providerId" : "client-x509"
}, {
  "requirement" : "ALTERNATIVE",
  "displayName" : "Signed JWT - Federated",
  "providerId" : "federated-jwt"
} ]

What you see: Five methods, all ALTERNATIVE – one of them has to succeed. Which one applies to a client is set by the client itself. The last one, federated-jwt, is the badge exchange. In Keycloak 26.8 it is enabled out of the box; in older versions it was a preview feature that had to be unlocked with --features.

Step 4 – put up the cluster’s specimen card.

# on id1
/opt/keycloak/bin/kcadm.sh create identity-provider/instances -r gebaeude -s alias=cluster -s providerId=kubernetes -s config.issuer=https://172.16.0.126:6443
Option Value Meaning
-r gebaeude in this realm
alias cluster name by which clients refer to this provider
providerId kubernetes type: trust in a Kubernetes issuer
config.issuer https://172.16.0.126:6443 the issuer from Day 3; Keycloak fetches discovery document and JWKS there

Expected:

Created new instance with id 'cluster'
# on id1
/opt/keycloak/bin/kcadm.sh get identity-provider/instances/cluster -r gebaeude

Expected:

{
  "alias" : "cluster",
  "internalId" : "e79ded3a-0fff-499e-bb06-c5f7aac542d0",
  "providerId" : "kubernetes",
  "enabled" : true,
  "hideOnLogin" : true,
  "config" : {
    "issuer" : "https://172.16.0.126:6443"
  },
  "types" : [ "CLIENT_ASSERTION" ]
}

What you see: types: CLIENT_ASSERTION – this provider does not log in people, it only checks badges of programs. That is also why hideOnLogin is set: it does not show up on the login page.

And this is the reason for Day 3: there is only an address here. Keycloak fetches the specimen card itself and without a badge – that only works because discovery document and JWKS have been public since Day 3.

Step 5 – the account for the till.

# on id1
/opt/keycloak/bin/kcadm.sh create clients -r gebaeude -s clientId=kasse -s publicClient=false -s standardFlowEnabled=false -s serviceAccountsEnabled=true -s clientAuthenticatorType=federated-jwt -s 'attributes."jwt.credential.issuer"=cluster' -s 'attributes."jwt.credential.sub"=system:serviceaccount:laden:kasse'
Option Value Meaning
clientId kasse name of the client
publicClient false confidential client: must identify itself
standardFlowEnabled false no login of people via the browser
serviceAccountsEnabled true client may log in by itself (client credentials grant)
clientAuthenticatorType federated-jwt credential: “Signed JWT – Federated”
jwt.credential.issuer cluster alias of the identity provider, not the URL
jwt.credential.sub system:serviceaccount:laden:kasse this sub in the building badge belongs to this client

The single quotes around the two attributes settings are necessary: the attribute names contain dots, and kcadm.sh would otherwise read them as nested fields.

Expected (your ID will be different):

Created new client with id '57596c70-d4c1-4afd-93e9-c526d8f1e413'

Step 6 – check what was registered.

# on id1
/opt/keycloak/bin/kcadm.sh get clients -r gebaeude -q clientId=kasse > ~/kurs/04/kasse-client.json
# on id1
jq '.[0] | {clientId, clientAuthenticatorType, serviceAccountsEnabled, attributes}' ~/kurs/04/kasse-client.json

Expected:

{
  "clientId": "kasse",
  "clientAuthenticatorType": "federated-jwt",
  "serviceAccountsEnabled": true,
  "attributes": {
    "realm_client": "false",
    "client.secret.creation.time": "1796121808",
    "jwt.credential.sub": "system:serviceaccount:laden:kasse",
    "jwt.credential.issuer": "cluster"
  }
}

What you see: The two attributes are there. And one line that makes you pause: client.secret.creation.time. Keycloak generated a client secret anyway – it is in the file’s secret field. Whether it is any good, you check in Drill 6.

Why the detour via the file? kcadm.sh get … --fields attributes shows an empty {} for attribute names with dots – tried out in the lab. Do not let that fool you.

Remember: The identity provider says whom Keycloak trusts (the issuer); the client says who may log in with it (exactly one sub). Together they replace the password.

Save your progress? Sign up for free

Drill 5: Building badge for a day pass

Where you are: on id1.

What you have afterwards: a pod kasse with a badge for the central badge office and an access token from Keycloak that the pod got without any secret.

Step 1 – a second badge for the till. The pod kasse from Day 2 has a projected badge for the warehouse door. It gets a second one whose audience is the realm’s address. You start with a copy:

# on id1
cp ~/kurs/02/kasse-v2.yaml ~/kurs/04/kasse-v3.yaml
# on id1
nano ~/kurs/04/kasse-v3.yaml
kurs/04/kasse-v3.yaml changes in green
apiVersion: v1
kind: Pod
metadata:
  name: kasse
  namespace: laden
spec:
  serviceAccountName: kasse
  automountServiceAccountToken: false
  containers:
    - name: shell
      image: curlimages/curl:8.17.0
      command: ["sleep", "infinity"]
      volumeMounts:
        - name: lager-ausweis
          mountPath: /var/run/secrets/lager
          readOnly: true
        - name: empfang-ausweis
          mountPath: /var/run/secrets/empfang
          readOnly: true
  volumes:
    - name: lager-ausweis
      projected:
        sources:
          - serviceAccountToken:
              audience: lager
              expirationSeconds: 600
              path: token
    - name: empfang-ausweis
      projected:
        sources:
          - serviceAccountToken:
              audience: http://172.16.0.126:8080/realms/gebaeude
              expirationSeconds: 600
              path: token
Option Value Meaning
audience http://172.16.0.126:8080/realms/gebaeude audience = the realm’s issuer address; that is exactly what Keycloak expects
expirationSeconds 600 ten minutes; the kubelet renews after about eight (Day 2)
mountPath /var/run/secrets/empfang separate folder, apart from the warehouse badge

Step 2 – replace the pod. The volumes of a running pod cannot be changed; the pod has to be recreated:

# on id1
kubectl delete pod kasse -n laden
# on id1
kubectl apply -f ~/kurs/04/kasse-v3.yaml
# on id1
kubectl wait --for=condition=Ready pod/kasse -n laden --timeout=60s

Expected:

pod/kasse condition met

Step 3 – look at the badge.

# on id1
kubectl exec -n laden kasse -- cat /var/run/secrets/empfang/token > ~/kurs/04/empfang.jwt
# on id1
step crypto jwt inspect --insecure < ~/kurs/04/empfang.jwt

Expected (excerpt – look for aud, exp, iat, iss and sub):

    "aud": [
      "http://172.16.0.126:8080/realms/gebaeude"
    ],
    "exp": 1796122480,
    "iat": 1796121880,
    "iss": "https://172.16.0.126:6443",
    "sub": "system:serviceaccount:laden:kasse"

What you see: Everything Keycloak needs: the issuer from the identity provider, the subject from the client, the realm’s audience, ten minutes of lifetime.

Step 4 – the exchange. The pod sends its badge to Keycloak’s token endpoint. The image curlimages/curl comes with curl:

# on id1
kubectl exec -n laden kasse -- curl -s http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/token --data-urlencode grant_type=client_credentials --data-urlencode client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer --data-urlencode client_assertion@/var/run/secrets/empfang/token > ~/kurs/04/antwort.json
Option Value Meaning
Address …/realms/gebaeude/protocol/openid-connect/token the realm’s token endpoint
grant_type client_credentials the program logs in on its own behalf
client_assertion_type urn:ietf:params:oauth:client-assertion-type:jwt-bearer “my credential is a JWT” (RFC 7523)
client_assertion@datei the building badge @ reads the value from the file – the token never appears on the command line

You do not send a client_id. Keycloak finds the client via the issuer and the sub in the badge.

# on id1
jq . ~/kurs/04/antwort.json

Expected (the token is shortened):

{
  "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJQX2pUSWo5Qmxw…",
  "expires_in": 300,
  "refresh_expires_in": 0,
  "token_type": "Bearer",
  "not-before-policy": 0,
  "scope": "profile email"
}

What you see: An access token, valid for 300 seconds, without a refresh token (refresh_expires_in: 0). If the till needs another one in five minutes, it exchanges again – after all, the kubelet keeps renewing its building badge.

Step 5 – what the day pass says.

# on id1
jq -r .access_token ~/kurs/04/antwort.json > ~/kurs/04/zugang.jwt
# on id1
step crypto jwt inspect --insecure < ~/kurs/04/zugang.jwt

Expected (excerpt):

    "kid": "P_jTIj9BlpOQpFejsgROS8PhIg8JkavzkcGRV3xXbKI",
    "exp": 1796122191,
    "iat": 1796121891,
    "iss": "http://172.16.0.126:8080/realms/gebaeude",
    "aud": "account",
    "sub": "429f53af-99a9-4f81-b455-fb27360d4795",
    "azp": "kasse",
    "preferred_username": "service-account-kasse",
    "clientAddress": "10.42.0.8",
    "client_id": "kasse"
Field Value Meaning
kid P_jT… a key of Keycloak, not the cluster’s
iss realm address the issuer is now Keycloak
sub UUID the client’s service user in Keycloak
azp, client_id kasse which client it was issued for
preferred_username service-account-kasse readable name of the service user
clientAddress 10.42.0.8 address the request came from

What you see: Two badges, two issuers. The building badge from the cluster was only the entry ticket. Applications that trust Keycloak only see Keycloak’s day pass and do not need to know anything about the cluster.

Remember: The pod exchanges a badge that the kubelet keeps reissuing for it for a badge of the central office. Nowhere is there a secret that lives longer than ten minutes.

Save your progress? Sign up for free

Drill 6: Who does not get in – and who does

Where you are: on id1.

What you have afterwards: measured limits of federation: wrong door, wrong name, secret, lifetime, reuse.

To keep the commands short, you write the address and the fixed form fields into variables once:

# on id1
URL=http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/token
# on id1
TYP=urn:ietf:params:oauth:client-assertion-type:jwt-bearer

All curl commands in this drill run in your home directory. The shell does not expand ~ after @, which is why relative paths are used there.

# on id1
cd

Step 1 – the same badge twice. In Drill 5 the till already used its badge. Once more:

# on id1
kubectl exec -n laden kasse -- curl -s $URL --data-urlencode grant_type=client_credentials --data-urlencode client_assertion_type=$TYP --data-urlencode client_assertion@/var/run/secrets/empfang/token -o /dev/null -w '%{http_code}\n'
  • -o /dev/null – discard the response,
  • -w '%{http_code}\n' – print only the HTTP status code.

Your shell on id1 fills in $URL and $TYP before kubectl exec sends the command into the pod.

Expected:

200

What you see: Accepted. For Kubernetes badges Keycloak explicitly allows reuse, because the kubelet only renews the badge every few minutes, and the pod needs new access tokens in between.

Step 2 – the same badge, but from outside. You copied the file empfang.jwt out of the pod in Drill 5. Now you send it directly from id1, as if someone had stolen it:

# on id1
curl -s $URL --data-urlencode grant_type=client_credentials --data-urlencode client_assertion_type=$TYP --data-urlencode client_assertion@kurs/04/empfang.jwt -o /dev/null -w '%{http_code}\n'

Expected:

200

What you see: Accepted as well. Keycloak does not check where the badge comes from, only whether it is genuine. A building badge is a bearer token: whoever holds it is the till – until it expires. That is the same lesson as on Day 1, only with a deadline of ten minutes instead of “forever”.

Step 3 – the badge for the wrong door. The till’s warehouse badge is genuine and from the right issuer, but for the audience lager:

# on id1
kubectl exec -n laden kasse -- curl -s $URL --data-urlencode grant_type=client_credentials --data-urlencode client_assertion_type=$TYP --data-urlencode client_assertion@/var/run/secrets/lager/token

Expected:

{"error":"invalid_client","error_description":"Invalid token audience"}

Step 4 – a genuine badge, but not on the list. The ServiceAccount lager-pruefer from Day 2 gets a badge with the correct audience:

# on id1
kubectl create token lager-pruefer -n laden --audience http://172.16.0.126:8080/realms/gebaeude --duration 10m > ~/kurs/04/pruefer.jwt
# on id1
curl -s $URL --data-urlencode grant_type=client_credentials --data-urlencode client_assertion_type=$TYP --data-urlencode client_assertion@kurs/04/pruefer.jwt

Expected:

{"error":"invalid_client","error_description":"Invalid client or Invalid client credentials"}

Step 5 – what the badge office writes down. The response to the client is deliberately vague. The journal says more:

# on id1
sudo journalctl -u keycloak --no-pager -o cat --since "-5min" --grep "CLIENT_LOGIN_ERROR"

Expected (excerpt – two lines, wrapped; timestamps and the fields realmId, userId and client_assertion_id omitted):

WARN  [org.keycloak.events] (executor-thread-1) type="CLIENT_LOGIN_ERROR", realmName="gebaeude",
  clientId="kasse", ipAddress="10.42.0.8", error="invalid_client_credentials",
  client_assertion_issuer="https://172.16.0.126:6443",
  client_assertion_sub="system:serviceaccount:laden:kasse", grant_type="client_credentials"
WARN  [org.keycloak.events] (executor-thread-1) type="CLIENT_LOGIN_ERROR", realmName="gebaeude",
  clientId="null", ipAddress="172.16.0.126", error="client_not_found",
  client_assertion_issuer="https://172.16.0.126:6443",
  client_assertion_sub="system:serviceaccount:laden:lager-pruefer", grant_type="client_credentials"

What you see: The badge office’s visitor log. The first entry is the warehouse badge (client found, badge wrong), the second the verifier (no client with this sub). Issuer and subject are listed each time – that is how you later find out which pod tried it.

Step 6 – and the master key? In Drill 4 you saw that Keycloak generated a secret for the client. You take it from the file and try it:

# on id1
jq -r '.[0].secret' ~/kurs/04/kasse-client.json > ~/kurs/04/kasse-secret.txt
# on id1
curl -s $URL --data-urlencode grant_type=client_credentials --data-urlencode client_id=kasse --data-urlencode client_secret@kurs/04/kasse-secret.txt

Expected:

{"error":"invalid_client","error_description":"Invalid client or Invalid client credentials"}

What you see: Rejected. The client is set to federated-jwt, so only this method counts. The secret is in the record but opens nothing. Delete the file anyway – a secret lying around will be used sooner or later, as soon as someone switches the client over:

# on id1
rm ~/kurs/04/kasse-secret.txt

Step 7 – how long is a building badge valid at the central office? Kubernetes issues badges with lifetimes of up to an hour and more. Keycloak accepts at most 3600 seconds for Kubernetes badges. You try a badge with two hours:

# on id1
kubectl create token kasse -n laden --audience http://172.16.0.126:8080/realms/gebaeude --duration 2h > ~/kurs/04/lang.jwt
# on id1
curl -s $URL --data-urlencode grant_type=client_credentials --data-urlencode client_assertion_type=$TYP --data-urlencode client_assertion@kurs/04/lang.jwt -o /dev/null -w '%{http_code}\n'

Expected:

200

Surprise: accepted. Keycloak does not compute exp - iat; instead, when the badge is presented, it checks whether more than 3600 seconds have passed since iat. So a badge that is too long is valid in its first hour. You will see what happens after that in Step 8.

# on id1
step crypto jwt inspect --insecure < ~/kurs/04/lang.jwt

Expected (excerpt):

    "exp": 1796129131,
    "iat": 1796121931,

iat is 10:45:31 UTC. Write down this time plus one hour.

Step 8 – the same card an hour later. Wait until the time you wrote down has passed, and send lang.jwt again. According to exp it is valid for another hour:

# on id1
date -u +%T

Expected (a different time for you, but after iat + 1 hour):

11:47:01
# on id1
curl -s $URL --data-urlencode grant_type=client_credentials --data-urlencode client_assertion_type=$TYP --data-urlencode client_assertion@kurs/04/lang.jwt

Expected:

{"error":"invalid_client","error_description":"Token was issued too far in the past to be used now"}

What you see: Kubernetes still considers the badge valid for another hour, Keycloak no longer does. For the central badge office the issue date is what counts: a building badge is usable there for at most one hour after iat, no matter what exp says. The kubelet renews projected tokens with 600 seconds long before that – they never notice.

Remember: Keycloak checks the issuer, the list, the seal, the door and the age of the badge – but not who presents it and how often. Short lifetimes remain the actual safeguard.

Save your progress? Sign up for free

Diagnosis task

A colleague “tidied up” keycloak.conf and restarted Keycloak. Since then the till no longer gets a day pass:

# on id1
kubectl exec -n laden kasse -- curl -s $URL --data-urlencode grant_type=client_credentials --data-urlencode client_assertion_type=$TYP --data-urlencode client_assertion@/var/run/secrets/empfang/token

Expected:

{"error":"invalid_client","error_description":"Invalid client or Invalid client credentials"}

Nothing has changed on the client, nor on the cluster. What is going on?

Solution path:

  1. The response to the client deliberately reveals little. So go to the journal, this time looking for warnings in general:

    # on id1
    sudo journalctl -u keycloak --no-pager -o cat --since "-5min" --grep "Failed to load|CLIENT_LOGIN_ERROR"

    Expected (excerpt – first line, wrapped):

    WARN  [org.keycloak.broker.kubernetes.KubernetesIdentityProvider] (executor-thread-1)
      Failed to load public keys for Kubernetes IdP 'cluster' with issuer 'https://172.16.0.126:6443':
      java.lang.RuntimeException: Error when loading public keys: javax.net.ssl.SSLHandshakeException:
      (certificate_unknown) PKIX path building failed: …
      unable to find valid certification path to requested target
  2. PKIX path building failed means, in plain words: Java does not know the CA that issued the API server’s certificate. Keycloak cannot fetch the specimen card and therefore rejects every badge.

  3. A look at the configuration:

    # on id1
    cat /opt/keycloak/conf/keycloak.conf

    Expected:

    # Ausweisstelle des Bürogebäudes – Laborbetrieb (start-dev)
    http-host=0.0.0.0
    http-port=8080
    hostname=http://172.16.0.126:8080

    The line truststore-paths is missing.

  4. Solution: Add the line again (sudo nano /opt/keycloak/conf/keycloak.conf), restart Keycloak, wait for the startup in the journal. At startup Keycloak reports the truststore:

    # on id1
    sudo journalctl -u keycloak --no-pager -o cat --since "-1min" --grep "truststore"

    Expected:

    2026-12-01 10:47:02,556 INFO  [org.keycloak.truststore.TruststoreBuilder] (main) Found the following truststore files in the truststore paths [/opt/keycloak/conf/cluster-ca.crt]

    After that the command from the beginning with -o /dev/null -w '%{http_code}\n' returns 200 again.

Why did it work until the restart? Keycloak only reads keycloak.conf at startup. And according to the source code (KubernetesIdentityProvider), Keycloak keeps keys in memory once loaded and only reloads the JWKS when a badge with an unknown kid arrives. So a truststore error only shows up when a reload is needed. The second case is treacherous: if the cluster changes its signing key, federation can fail even though nobody has touched Keycloak for months. You did not reproduce this case in the lab.

Challenge

The warehouse verifier from Step 4 of Drill 6 should also get a day pass – with its own client, without a secret. Write down the commands before you read the solution.

Solution: A second client with the verifier’s sub. The identity provider stays the same – one specimen card is enough for all of the building’s badges.

# on id1
/opt/keycloak/bin/kcadm.sh create clients -r gebaeude -s clientId=lager-pruefer -s publicClient=false -s standardFlowEnabled=false -s serviceAccountsEnabled=true -s clientAuthenticatorType=federated-jwt -s 'attributes."jwt.credential.issuer"=cluster' -s 'attributes."jwt.credential.sub"=system:serviceaccount:laden:lager-pruefer'

Expected (your ID will be different):

Created new client with id 'b4ce0531-f2ed-4930-b1f4-f92910cc8a5c'

A fresh badge – the one from Drill 6 may already have expired:

# on id1
kubectl create token lager-pruefer -n laden --audience http://172.16.0.126:8080/realms/gebaeude --duration 10m > ~/kurs/04/pruefer.jwt
# on id1
curl -s $URL --data-urlencode grant_type=client_credentials --data-urlencode client_assertion_type=$TYP --data-urlencode client_assertion@kurs/04/pruefer.jwt -o ~/kurs/04/pruefer-antwort.json
# on id1
jq -r .access_token ~/kurs/04/pruefer-antwort.json > ~/kurs/04/pruefer-zugang.jwt
# on id1
step crypto jwt inspect --insecure < ~/kurs/04/pruefer-zugang.jwt

Expected (excerpt):

    "azp": "lager-pruefer",
    "preferred_username": "service-account-lager-pruefer",
    "client_id": "lager-pruefer"

Each ServiceAccount gets its own client. Two pods with the same ServiceAccount would be indistinguishable to Keycloak; that is why you never federate the ServiceAccount default.

Save your progress? Sign up for free

Checkpoint

# on id1
systemctl is-active keycloak

Expected:

active
# on id1
/opt/keycloak/bin/kcadm.sh get identity-provider/instances/cluster -r gebaeude

Expected: "providerId" : "kubernetes" and "issuer" : "https://172.16.0.126:6443".

# on id1
kubectl exec -n laden kasse -- curl -s http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/token --data-urlencode grant_type=client_credentials --data-urlencode client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer --data-urlencode client_assertion@/var/run/secrets/empfang/token -o /dev/null -w '%{http_code}\n'

Expected:

200
# on id1
grep -c service-account-issuer /etc/rancher/k3s/config.yaml

Expected:

1

Test yourself

  1. Why must the audience of the building badge be exactly http://172.16.0.126:8080/realms/gebaeude and not, say, keycloak?
  2. Keycloak is installed, running and answers on id1 to curl localhost:8080. A pod gets Couldn't connect to server. What is the cause?
  3. What happens if you register system:serviceaccount:laden:default as the federated subject of the client kasse?
  4. An attacker copies the badge from /var/run/secrets/empfang/token. What can they do with it, and for how long?
  5. Federation ran for three months; suddenly Keycloak rejects all badges. The journal says PKIX path building failed. What could have changed, even though nobody touched Keycloak?
  6. Why does Keycloak not need a badge of its own to read the cluster’s specimen card?

Answers:

  1. Keycloak expects the realm’s own issuer address as the audience. A badge for keycloak would fail as in Step 3 of Drill 6: Invalid token audience. The address comes from hostname – that is why it has to be fixed.
  2. In development mode Keycloak 26.8 only listens on 127.0.0.1. Only http-host=0.0.0.0 opens the door to the outside; ss -ltnp shows it.
  3. Then every pod in the namespace laden that uses the ServiceAccount default may log in as the till – and that is all pods that do not have their own.
  4. They can log in to Keycloak as kasse and fetch access tokens, as often as they like (Step 2 of Drill 6). That works until the badge expires – at most ten minutes after issuance, and at Keycloak at most one hour after iat anyway.
  5. Keycloak keeps the keys in memory and only reloads them when needed – after a restart or for an unknown kid. Typical triggers: someone restarted Keycloak after the truststore was changed, or the API server’s certificate now comes from a different CA than the one in the truststore.
  6. Because discovery document and JWKS have been readable for system:unauthenticated since Day 3. Without Day 3, Keycloak would need a ServiceAccount token from the cluster – which only works if Keycloak runs in the cluster.

Interview note

“How does a pod log in to an identity provider without a client secret?” – Good answer: with a projected ServiceAccount token as a client assertion according to RFC 7523, client credentials grant. The identity provider trusts the cluster’s issuer and fetches its JWKS via the public discovery address; the client is bound to exactly one sub, system:serviceaccount:<namespace>:<name>. The token’s audience is the identity provider itself. Keycloak has supported this as a preview since 26.5; in 26.8 it is standard. AWS, Azure and Google use the same pattern for Workload Identity Federation. If they dig deeper: the token is a bearer token and may be reused – hence short expirationSeconds and TLS to the identity provider.

Enterprise note

The lab takes three shortcuts that do not work in production. First, HTTP: the building badge travels across the network in plain text, and anyone listening in can use it for ten minutes. Keycloak belongs behind TLS (https-certificate-file, https-certificate-key-file), with start instead of start-dev. Second, the H2 file: for production you use PostgreSQL and at least two Keycloak instances. Third, the administrator: the temporary admin is replaced by a real administrator, ideally one who logs in via an identity provider themselves.

For the download: the SHA-1 checksum protects against broken downloads, not against an attacker. Many organizations therefore use the official container image with a pinned digest (@sha256:…) or build Keycloak from a verified mirror.

And a warning from the journal: for every client with “Full scope allowed”, Keycloak reports that the switch is deprecated. A day pass of the till therefore contains all roles of the realm. In production you turn this off and give each client only the roles it needs – more on this on Day 9.

Summary

  • The old issuer has been removed; that was safe because no valid token carried it any more.
  • Keycloak 26.8.2 runs on id1 as a systemd service under its own user, in development mode, reachable at the fixed address http://172.16.0.126:8080.
  • In development mode Keycloak only listens on localhost until http-host is set.
  • truststore-paths makes the cluster CA trusted by Keycloak; without it, loading the keys fails with PKIX path building failed.
  • The identity provider of type kubernetes needs only the issuer address; the client with federated-jwt is bound to exactly one sub.
  • The pod exchanges a projected token with audience = realm address for an access token from Keycloak – without a secret.
  • Rejected: wrong audience, unknown sub, the client secret, badges with an iat older than one hour. Accepted: the same badge several times and from anywhere.

Commands at a glance

Command What for
sha1sum <datei> compute a checksum and compare it with the .sha1 file
sudo useradd --system --home-dir <dir> --shell /usr/sbin/nologin <name> system user for a service
sudo -u keycloak /opt/keycloak/bin/kc.sh bootstrap-admin user --username admin create the first administrator
kc.sh start-dev start Keycloak in development mode
sudo ss -ltnp sport = :8080 who listens on port 8080, and on which address
kcadm.sh config credentials --server … --realm master --user admin log kcadm.sh in
kcadm.sh create realms -s realm=<name> -s enabled=true create a realm
kcadm.sh create identity-provider/instances -r <realm> -s providerId=kubernetes -s config.issuer=<iss> trust the cluster
kcadm.sh create clients … -s clientAuthenticatorType=federated-jwt -s 'attributes."jwt.credential.sub"=…' client without a secret
curl … --data-urlencode client_assertion@<datei> send a badge as a client assertion
journalctl -u keycloak --grep CLIENT_LOGIN_ERROR rejected logins with reason

Contents

More