Skip to content
Hands-on IT IT Drills

Appendix B: Final Exam

Goal: Show without instructions that you can run Keycloak: create clients and users, end sessions, slow down attacks, back up and maintain everything as code. · Duration: approx. 90 min · Prerequisite: Day 15

Rules of Play

  • Each exercise describes only the goal. You find the path yourself; the days in parentheses help you look things up.
  • Each exercise ends with a check block: individual commands with what they must show. Only when all of them match does the exercise count.
  • Work in ~/kc-lab/anhb. Exercise 6 requires Terraform; everything else works with kcadm, curl or the console.
source ~/kc-lab/setup/env.sh
mkdir -p ~/kc-lab/anhb && cd ~/kc-lab/anhb
kclogin
api() { docker run --rm --network lab curlimages/curl:8.17.0 -s "$@"; }
uid() { kcadm get users -r lab -q username=$1 -q exact=true | jq -r '.[0].id'; }

Exercise 1: An App for the Phone

In the realm lab, create the client notes-mobile: public (without a secret), authorization code only, PKCE with S256 mandatory, redirect to http://localhost:8765/cb. (Day 3, Day 4)

Check block:

kcadm get clients -r lab -q clientId=notes-mobile | jq -c '.[0] | {publicClient,
  directAccessGrantsEnabled, pkce: .attributes["pkce.code.challenge.method"]}'
A="$KC_URL/realms/lab/protocol/openid-connect/auth?client_id=notes-mobile"
A="$A&response_type=code&scope=openid&redirect_uri=http://localhost:8765/cb"
curl -s -o /dev/null -w '%{redirect_url}\n' "$A" | grep -o 'error_description=[^&]*'

Expected:

{"publicClient":true,"directAccessGrantsEnabled":false,"pkce":"S256"}
error_description=Missing+parameter%3A+code_challenge_method

Without code_challenge, Keycloak sends the browser back with an error.

Solution

kcadm create clients -r lab -s clientId=notes-mobile -s publicClient=true \
  -s standardFlowEnabled=true -s directAccessGrantsEnabled=false \
  -s 'redirectUris=["http://localhost:8765/cb"]' \
  -s 'attributes."pkce.code.challenge.method"=S256'

Expected:

Created new client with id '…'

Save your progress? Sign up for free

Exercise 2: A New Colleague

lena ([email protected], password lab-user-pw-lena) should be allowed to write in notes – through the group, not through directly assigned roles. (Day 2, Day 4)

Check block:

kcadm get users/$(uid lena)/groups -r lab | jq -r '.[].name'
api -o /dev/null -w '%{http_code}\n' \
  -H "Authorization: Bearer $(token lena lab-user-pw-lena)" \
  -H 'Content-Type: application/json' -d '{"text":"von lena"}' notes-api:8080/notes

Expected:

team-notes
201

Solution

kcadm create users -r lab -s username=lena -s enabled=true -s [email protected] \
  -s emailVerified=true -s firstName=Lena -s lastName=Neu
kcadm set-password -r lab --username lena --new-password lab-user-pw-lena
GID=$(kcadm get groups -r lab -q search=team-notes \
  | jq -r '.[] | select(.name=="team-notes") | .id')
kcadm update users/$(uid lena)/groups/$GID -r lab -n

Expected:

Created new user with id '…'

Save your progress? Sign up for free

Exercise 3: All of ben’s Sessions

ben’s laptop has been stolen. End all of his sessions so that his refresh tokens are worthless as well. (Day 3, Day 12)

Check block:

kcadm get users/$(uid ben)/sessions -r lab | jq length
curl -s -d grant_type=refresh_token -d client_id=notes-cli \
  -d client_secret=lab-client-secret-123 -d refresh_token=$(cat ben.refresh) \
  $KC_URL/realms/lab/protocol/openid-connect/token | jq -c '{error, error_description}'

Expected:

0
{"error":"invalid_grant","error_description":"Session not active"}

You create the refresh token in ben.refresh beforehand – it stands for “ben was logged in”:

curl -s -d grant_type=password -d client_id=notes-cli \
  -d client_secret=lab-client-secret-123 -d username=ben -d password=lab-user-pw-456 \
  $KC_URL/realms/lab/protocol/openid-connect/token | jq -r .refresh_token > ben.refresh

Solution

kcadm create users/$(uid ben)/logout -r lab

In the console: Users → ben → Sessions → Sign out all sessions. Access tokens remain valid until they expire – one reason for short lifetimes.

Save your progress? Sign up for free

Exercise 4: Less Sensitive

Day 10 locks after three failed attempts. Change the realm to five attempts and two minutes of wait time. (Day 10)

Check block:

kcadm get realms/lab --fields bruteForceProtected,failureFactor,waitIncrementSeconds

Expected:

{
  "bruteForceProtected" : true,
  "waitIncrementSeconds" : 120,
  "failureFactor" : 5
}

Solution

kcadm update realms/lab -s failureFactor=5 -s waitIncrementSeconds=120

Save your progress? Sign up for free

Exercise 5: Backing Up the Partner

Export the realm partner including users as ~/kc-lab/anhb/partner-realm.json. (Day 12)

Check block:

jq -r '.realm' ~/kc-lab/anhb/partner-realm.json
jq -r '.users[].username' ~/kc-lab/anhb/partner-realm.json | sort

Expected: the realm with pia and the copy of anna from the SAML login.

partner
anna
pia

Solution

cd ~/kc-lab/keycloak
docker compose run --rm --no-deps -v ~/kc-lab/anhb:/export keycloak \
  export --dir /export --realm partner --users realm_file 2>&1 \
  | grep -o 'KC-SERVICES0035.*'
cd ~/kc-lab/anhb

Expected:

KC-SERVICES0035: Export finished successfully

Save your progress? Sign up for free

Exercise 6: uwe as Code

uwe ([email protected], password lab-user-pw-uwe) joins the group berichte – created with Terraform in the project from Day 13, in a file of its own, uwe.tf. (Day 13)

Check block:

jwt "$(token uwe lab-user-pw-uwe)" \
  | jq -c '[.realm_access.roles[] | select(startswith("notes"))]'
cd ~/kc-lab/terraform
terraform plan -no-color -detailed-exitcode >/dev/null; echo "exit=$?"
cd ~/kc-lab/anhb

Expected:

["notes-berichte"]
exit=0

Solution

cd ~/kc-lab/terraform
export TF_VAR_kc_url=$KC_URL TF_VAR_client_secret=lab-client-secret-123
cat > uwe.tf <<'EOF'
resource "keycloak_user" "uwe" {
  realm_id   = data.keycloak_realm.lab.id
  username   = "uwe"
  email      = "[email protected]"
  first_name = "Uwe"
  last_name  = "Bericht"
  initial_password {
    value     = "lab-user-pw-uwe"
    temporary = false
  }
}

resource "keycloak_user_groups" "uwe" {
  realm_id  = data.keycloak_realm.lab.id
  user_id   = keycloak_user.uwe.id
  group_ids = [keycloak_group.berichte.id]
}
EOF
terraform apply -auto-approve -no-color | grep -E 'Apply complete'
cd ~/kc-lab/anhb

Expected:

Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

Save your progress? Sign up for free

Knowledge Test

  1. Why doesn’t the password grant belong in a real application?
  2. What is the difference between a realm role and a client role in the token?
  3. Why does introspection return active:false even though the token is valid?
  4. A user was removed from a group in LDAP but may still write in Keycloak. What is the cause, and what helps?
  5. Why does an AD require an encrypted connection for the bind, and what does Keycloak need for it?
  6. Why do passkeys only work from Day 12 on?
  7. What happens to all tokens when KC_HOSTNAME changes?
  8. How does the operator know whether it may perform an upgrade as rolling?
  9. Why does Keycloak return the same message for a locked account as for a wrong password?
  10. What does not belong in Git when you manage Keycloak with Terraform?

Answers

  1. The application sees the password, MFA, passkeys and brokering don’t work, and required actions block it. Browser applications use authorization code with PKCE (Day 3, Day 10).
  2. Realm roles are under realm_access.roles, client roles under resource_access.<client>.roles – and they additionally put the client into aud (Day 5, Day 15).
  3. Since Keycloak 26, only a client that is in the token’s aud may introspect; the reason is in the log, not in the response (Day 3, Day 5).
  4. The user cache: Keycloak only reads groups again once the user is no longer in the cache. clear-user-cache or a shorter cache policy helps (Day 8).
  5. A simple bind sends the password along. That is why AD requires LDAPS; Keycloak needs the domain controller’s CA in its truststore and the right name in the certificate (Day 9).
  6. WebAuthn is only available in a secure context, that is, with HTTPS and a certificate the browser trusts (Day 10, Day 12).
  7. iss changes. Applications, brokers and SAML partners must know the new address; old tokens no longer match the issuer (Day 12).
  8. It runs an update job that compares the old and new version like kc.sh update-compatibility check (Day 12, Day 14).
  9. So that an attacker does not learn that they have locked an account – or that the account exists at all. The log shows the reason (Day 10, Day 15).
  10. The state (terraform.tfstate) and secrets. The state contains passwords and client secrets in plain text (Day 13).

Where to Go from Here?

  • Kong hands-on: Check Keycloak tokens at the API gateway, with plugins and rate limiting.
  • Kubernetes hands-on: the cluster under the operator, with Helm and RKE2.
  • Going further with Keycloak: Organizations for multi-tenant logins, custom providers (SPI) in Java, fine-grained admin permissions, Keycloakify for your own login pages.