Skip to content
Workload and AI agent identity · Chapter 10 of 20 Day 9: People – OIDC with Keycloak, signing in, reading tokens, scopes

Day 9: People – OIDC with Keycloak, signing in, reading tokens, scopes

Goal: create a visitor in Keycloak, sign her in to a program without a browser using the device sign-in, read and understand her three tokens, and use scopes to define what a token is valid for · Duration: about 90 min · Prerequisite: Day 4 completed (Keycloak is running, realm gebaeude exists), a browser on your machine that can reach 172.16.0.126:8080

Where we start

You have not used kcadm.sh since Day 4. The saved session has expired in the meantime:

# on id1
/opt/keycloak/bin/kcadm.sh get realms/gebaeude --fields realm,enabled

Expected:

Session has expired. Login again with 'kcadm.sh config credentials'

So sign in again, as on Day 4:

# on id1
/opt/keycloak/bin/kcadm.sh config credentials --server http://localhost:8080 --realm master --user admin

Expected:

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

Then the state of the realm:

# on id1
/opt/keycloak/bin/kcadm.sh get realms/gebaeude --fields realm,enabled,accessTokenLifespan,oauth2DeviceCodeLifespan,oauth2DevicePollingInterval

Expected:

{
  "realm" : "gebaeude",
  "accessTokenLifespan" : 300,
  "oauth2DeviceCodeLifespan" : 600,
  "oauth2DevicePollingInterval" : 5,
  "enabled" : true
}
# on id1
/opt/keycloak/bin/kcadm.sh get clients -r gebaeude --fields clientId

Expected:

[ {
  "clientId" : "account"
}, {
  "clientId" : "account-console"
}, {
  "clientId" : "admin-cli"
}, {
  "clientId" : "broker"
}, {
  "clientId" : "kasse"
}, {
  "clientId" : "lager-pruefer"
}, {
  "clientId" : "realm-management"
}, {
  "clientId" : "security-admin-console"
} ]
# on id1
/opt/keycloak/bin/kcadm.sh get users -r gebaeude --fields username

Expected:

[ ]

You need three numbers from the realm today: an access token is valid for 300 seconds, a device code for 600 seconds, and a device should poll at most every 5 seconds. So far there are clients only for machines (kasse, lager-pruefer), and no users at all.

Introduction

So far only machines have entered the building: pods with a building badge, services with a SPIFFE staff badge. From today on, people join them – and with them a completely different problem. A machine can read a key from a file. A person has a password in their head, and that password should be entered only at the badge office, never in a program that happens to need it.

Today’s program is a till terminal in the shop: a command-line tool without a browser, like kubectl, gh or az on a server. Anna Berger, who works in the shop, should sign in to it without typing her password into the terminal. That is what the device sign-in (Device Authorization Grant, RFC 8628) is for: the terminal shows a short code, Anna enters it in the browser on her phone or laptop, signs in to Keycloak there and gives her consent. The terminal then collects the tokens.

These tokens are the foundation for Days 10 to 13: there, an AI agent will act on Anna’s behalf, and for that you need to know exactly what is in Anna’s token.

Today you will learn:

  • how to create a user and a public client without a secret in Keycloak,
  • how the device sign-in works and what authorization_pending and slow_down mean,
  • the difference between ID token, access token and refresh token,
  • why an ID token does not open any door,
  • how scopes define what a token is valid for – and what happens when a program asks for more than it may,
  • how a program deals with an expired access token.

Background

The picture for today: the visitor pass at reception

Anna wants to work at the shop till. The till stands in the hall, has no reception desk of its own, and must never see Anna’s password. So it works like this:

  1. The till calls reception: “Someone here wants to sign in.” Reception gives the till a long case number that only the till knows, and a short queue number to read out, such as NHXB-IVMU.
  2. The till shows Anna the queue number: “Go to reception and give them this number.”
  3. Anna goes to reception, gives the queue number, shows her ID card (user name and password) and signs: “Yes, the till may see my profile and my e-mail address on my behalf.”
  4. Meanwhile, the till keeps asking with the case number: “Done yet?” – “Not yet.” If it asks too often, reception says: “Don’t push.”
  5. As soon as Anna has signed, the till receives three papers:
    • a business card with Anna’s name, addressed to the till – so the till knows who is standing in front of it (ID token),
    • a visitor pass for five minutes that Anna can show at doors (access token),
    • a claim ticket the till can use to get a new visitor pass from reception without Anna having to come again (refresh token).

The visitor pass also states which areas it is valid for – “profile”, “e-mail”, later “read warehouse”. Which areas a till may request at all is decided by reception, not by the till.

The terms

Term Meaning in the picture
User a person with an account in the realm Anna with her ID card
Public client program that cannot keep a secret safely till in the hall
Device Authorization Grant sign-in via a code the person enters somewhere else queue number at reception
device_code secret case number, only for the device the till’s case number
user_code short code for the person queue number to read out
Consent the person confirms what the program receives signature at reception
ID token tells the program who has signed in business card to the till
Access token opens doors at services, short-lived visitor pass, 5 minutes
Refresh token gets new access tokens as long as the session is alive claim ticket
Scope area a token is valid for access area on the pass
Session Anna’s sign-in at Keycloak, number sid entry in the visitor log

Remember: Only reception sees the password. The till gets papers that are valid briefly and say exactly what for.

Three tokens, three recipients

Token Recipient (aud) who verifies lifetime in the lab
ID token the client itself (ladenkasse-cli) the till 300 s
Access token a service (account, later the warehouse) every service, via JWKS 300 s
Refresh token Keycloak itself only Keycloak 1800 s

You check this table against real tokens in Drill 4.

Drill 1: Anna gets an account

Where you are: on id1, kcadm.sh signed in.

What you have afterwards: the user anna in the realm gebaeude with a password.

Step 1 – working folder.

# on id1
mkdir -p ~/kurs/09

Step 2 – create the user. Keycloak needs at least a user name. Name and e-mail address end up in the token later, so you provide them right away:

# on id1
/opt/keycloak/bin/kcadm.sh create users -r gebaeude -s username=anna -s firstName=Anna -s lastName=Berger -s [email protected] -s emailVerified=true -s enabled=true
Option Value Meaning
create users create a new user
-r gebaeude in the building’s realm, not in master
-s username= anna sign-in name
-s firstName= / lastName= Anna / Berger appears in the token as given_name, family_name, name
-s email= [email protected] e-mail address; .test is a reserved domain that will never exist
-s emailVerified= true the address counts as verified; otherwise Keycloak demands a verification e-mail at the first sign-in
-s enabled= true the account is active

Expected:

Created new user with id 'ebaf76a2-697c-40f3-910a-75e4d935cb6c'

Write down the ID. Yours will be different – use your own everywhere in this chapter.

Step 3 – check.

# on id1
/opt/keycloak/bin/kcadm.sh get users -r gebaeude -q username=anna --fields username,firstName,email,emailVerified,enabled,requiredActions
  • -q username=anna searches by user name.
  • --fields shows only these fields.

Expected:

[ {
  "username" : "anna",
  "firstName" : "Anna",
  "email" : "[email protected]",
  "emailVerified" : true,
  "enabled" : true,
  "requiredActions" : [ ]
} ]

What you see: requiredActions is empty. If it said UPDATE_PASSWORD or VERIFY_EMAIL, Keycloak would send Anna there first before her first sign-in – a common reason why a sign-in “hangs”.

Step 4 – the password. Without --new-password, kcadm.sh prompts for the password instead of requiring it on the command line. That way it ends up neither in the history nor in the process list:

# on id1
/opt/keycloak/bin/kcadm.sh set-password -r gebaeude --username anna
  • set-password sets a user’s password.
  • --username anna finds the user by name instead of by ID.

Expected:

Enter password:

Think of a password and remember it. No further message follows.

Remember: A password does not belong on the command line. If a tool can prompt for it, let it prompt.

Save your progress? Sign up for free

Drill 2: The till gets an entry

Where you are: on id1.

What you have afterwards: a public client ladenkasse-cli that may only use the device sign-in.

The till on Day 4 had a building badge from the cluster and could identify itself with it. Today’s shop till is a program that people download to their machines. Anyone can read what is inside it – a secret would not be secret there. That is why it is a public client: it signs in without a secret, and Keycloak relies on a person giving consent.

Step 1 – create the client.

# on id1
/opt/keycloak/bin/kcadm.sh create clients -r gebaeude -s clientId=ladenkasse-cli -s publicClient=true -s standardFlowEnabled=false -s directAccessGrantsEnabled=false -s 'attributes."oauth2.device.authorization.grant.enabled"=true'
Option Value Meaning
-s clientId= ladenkasse-cli name of the client
-s publicClient= true no secret; the client cannot identify itself
-s standardFlowEnabled= false no browser redirect back to the client (Authorization Code Flow); the till has no browser
-s directAccessGrantsEnabled= false forbids giving user name and password directly to the till (Password Grant)
-s 'attributes."oauth2.device.authorization.grant.enabled"=' true allows the device sign-in

The single quotes protect the double quotes from the shell; kcadm.sh needs the double quotes because the attribute name contains dots.

Expected:

Created new client with id 'cd9ee231-02bd-467c-82e8-d2c8b57ca8de'

Write down this ID too; you need it in Drill 5.

Step 2 – save the entry.

# on id1
/opt/keycloak/bin/kcadm.sh get clients -r gebaeude -q clientId=ladenkasse-cli > ~/kurs/09/cli-client.json

No output – it is in the file.

Step 3 – read it. As on Day 4, --fields does not display attributes with dots in their names correctly, so you read the file with jq:

# on id1
jq '.[0] | {clientId, publicClient, standardFlowEnabled, directAccessGrantsEnabled, device: .attributes["oauth2.device.authorization.grant.enabled"], defaultClientScopes, optionalClientScopes}' ~/kurs/09/cli-client.json
  • .[0] takes the first match. kcadm.sh get clients -q … always returns a list, even with exactly one match. Without .[0], jq reports Cannot index array with string "clientId".
  • {…} builds a new object from only these fields.
  • .attributes["…"] reads an attribute whose name contains dots.

Expected:

{
  "clientId": "ladenkasse-cli",
  "publicClient": true,
  "standardFlowEnabled": false,
  "directAccessGrantsEnabled": false,
  "device": "true",
  "defaultClientScopes": [
    "web-origins",
    "acr",
    "profile",
    "roles",
    "basic",
    "email"
  ],
  "optionalClientScopes": [
    "address",
    "phone",
    "organization",
    "offline_access",
    "microprofile-jwt"
  ]
}

What you see: Keycloak gave the client scopes on its own. Default scopes are in every token of this client, even if it does not ask for them. Optional scopes it gets only if it explicitly requests them. Whatever is in neither list it cannot get at all – you try that out in Drill 5.

Remember: Reception decides which areas a till may ask for at all. The till can only choose from this list.

Save your progress? Sign up for free

Drill 3: Signing in with a queue number

Where you are: on id1 and in a browser on your machine.

What you have afterwards: Anna’s tokens in ~/kurs/09/anmeldung.json.

Step 1 – where is reception? Every OIDC issuer publishes its addresses at a fixed address, like the cluster on Day 3:

# on id1
curl -s http://172.16.0.126:8080/realms/gebaeude/.well-known/openid-configuration -o ~/kurs/09/oidc.json -w "%{http_code}\n"
  • -o ~/kurs/09/oidc.json writes the response to the file.
  • -w "%{http_code}\n" then prints only the HTTP status.

Expected:

200
# on id1
jq '{issuer, device_authorization_endpoint, token_endpoint, userinfo_endpoint, grant_types_supported}' ~/kurs/09/oidc.json

Expected:

{
  "issuer": "http://172.16.0.126:8080/realms/gebaeude",
  "device_authorization_endpoint": "http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/auth/device",
  "token_endpoint": "http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/token",
  "userinfo_endpoint": "http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/userinfo",
  "grant_types_supported": [
    "authorization_code",
    "client_credentials",
    "implicit",
    "password",
    "refresh_token",
    "urn:ietf:params:oauth:grant-type:device_code",
    "urn:ietf:params:oauth:grant-type:jwt-bearer",
    "urn:ietf:params:oauth:grant-type:token-exchange",
    "urn:ietf:params:oauth:grant-type:uma-ticket",
    "urn:openid:params:grant-type:ciba"
  ]
}

What you see: three addresses you need today: where the till gets the queue number (device_authorization_endpoint), where it collects the tokens (token_endpoint), and where a service can look up the person behind an access token (userinfo_endpoint). The list of grant types already contains token-exchange – that comes on Day 11.

Step 2 – get the queue number. The till contacts reception and says who it is and what it wants:

# on id1
curl -s http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/auth/device -d client_id=ladenkasse-cli -d scope=openid -o ~/kurs/09/geraet.json -w "%{http_code}\n"
  • -d client_id=ladenkasse-cli – who is asking. There is no secret.
  • -d scope=openid – “I want to know who signs in”. Without openid there would be no ID token.
  • -d sends the data as a form via POST.

Expected:

200
# on id1
jq . ~/kurs/09/geraet.json

Expected (your codes will differ):

{
  "device_code": "1vwAOqRVVG3m8BgOBz6ntaqUOyYptjaCTYNwj0lfylc",
  "user_code": "NHXB-IVMU",
  "verification_uri": "http://172.16.0.126:8080/realms/gebaeude/device",
  "verification_uri_complete": "http://172.16.0.126:8080/realms/gebaeude/device?user_code=NHXB-IVMU",
  "expires_in": 600,
  "interval": 5
}
Field Value Meaning
device_code long, random case number; only the till knows it, never display it
user_code NHXB-IVMU queue number for Anna; short so it can be typed in
verification_uri …/device where Anna enters the queue number
verification_uri_complete with ?user_code= the same page with the code prefilled, good for a QR code
expires_in 600 ten minutes for the whole process (oauth2DeviceCodeLifespan from the starting state)
interval 5 how many seconds the till should wait between two polls

From now on the clock is ticking: ten minutes until step 7.

Step 3 – the case number into a file. For polling you need the device_code as a value. Instead of typing it, jq -r writes it into a file without quotes:

# on id1
jq -r .device_code ~/kurs/09/geraet.json > ~/kurs/09/geraet-code.txt

Step 4 – poll too early. The till asks reception whether Anna has already given consent:

# on id1
curl -s http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/token -d client_id=ladenkasse-cli -d grant_type=urn:ietf:params:oauth:grant-type:device_code --data-urlencode device_code@$HOME/kurs/09/geraet-code.txt
Option Value Meaning
-d client_id= ladenkasse-cli the same client as in step 2
-d grant_type= urn:ietf:params:oauth:grant-type:device_code “I am collecting tokens for a device sign-in”
--data-urlencode device_code@ file reads the value from the file; @ means “from file”

$HOME instead of ~: after @ the shell does not expand the tilde.

Expected:

{"error":"authorization_pending","error_description":"The authorization request is still pending"}

What you see: not an error in the real sense – “Anna has not been to reception yet”. A real program waits interval seconds and asks again.

Step 5 – poll too fast. Send the same command again right away, without waiting five seconds:

# on id1
curl -s http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/token -d client_id=ladenkasse-cli -d grant_type=urn:ietf:params:oauth:grant-type:device_code --data-urlencode device_code@$HOME/kurs/09/geraet-code.txt

Expected:

{"error":"slow_down","error_description":"Slow down"}

What you see: “Don’t push.” RFC 8628 requires a device to increase its interval by five seconds after slow_down. A program that ignores this puts load on reception for every waiting person.

Step 6 – Anna goes to reception. On your machine, open the verification_uri from step 2 in the browser, that is http://172.16.0.126:8080/realms/gebaeude/device, and type in the queue number:

The page for the queue number. This is where Anna enters the code the till displayed.

After Submit, Keycloak asks for user name and password. Sign in as anna with the password from Drill 1. Then comes the consent:

The consent page. Anna sees what the till is to receive on her behalf.

The three items are the default scopes from Drill 2: profile (“User profile”), roles (“User roles”) and email (“Email address”). Confirm with Yes:

Done. From now on the till gets its tokens.

The interface is in English because the realm has no further languages enabled. What reception looks like is decided by the realm, not by the till – the till has never seen this page.

Step 7 – collect the tokens. The same command as in step 4, this time with the response written to a file:

# on id1
curl -s http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/token -d client_id=ladenkasse-cli -d grant_type=urn:ietf:params:oauth:grant-type:device_code --data-urlencode device_code@$HOME/kurs/09/geraet-code.txt -o ~/kurs/09/anmeldung.json -w "%{http_code}\n"

Expected:

200
# on id1
jq 'del(.access_token, .id_token, .refresh_token)' ~/kurs/09/anmeldung.json

del(…) leaves out the three long tokens so that you see the rest.

Expected:

{
  "expires_in": 300,
  "refresh_expires_in": 1800,
  "token_type": "Bearer",
  "not-before-policy": 0,
  "session_state": "d3unt_BrIlLge_PNYwtU72ZJ",
  "scope": "openid profile email"
}

What you see: There are three tokens in the file (you hid them with del). The access token is valid for 300 seconds, the refresh token for 1800. session_state is the number of Anna’s session in the visitor log.

Step 8 – the case number a second time.

# on id1
curl -s http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/token -d client_id=ladenkasse-cli -d grant_type=urn:ietf:params:oauth:grant-type:device_code --data-urlencode device_code@$HOME/kurs/09/geraet-code.txt

Expected:

{"error":"invalid_grant","error_description":"Device code not valid"}

What you see: The case number is valid exactly once. Whoever finds it later gets nothing.

Remember: Queue number for the person, case number for the device. Only the browser saw the password, and the case number is used up after collection.

Save your progress? Sign up for free

Drill 4: Reading three papers

Where you are: on id1. The access token is valid for only five minutes – work through steps 1 to 6 quickly. If it expires, that is no disaster: that is exactly the diagnosis task.

What you have afterwards: the three tokens as files and proof of who accepts which one.

Step 1 – separate the three tokens. One jq -r per token:

# on id1
jq -r .access_token ~/kurs/09/anmeldung.json > ~/kurs/09/anna-zugang.jwt
# on id1
jq -r .id_token ~/kurs/09/anmeldung.json > ~/kurs/09/anna-id.jwt
# on id1
jq -r .refresh_token ~/kurs/09/anmeldung.json > ~/kurs/09/anna-erneuern.txt

No output. The refresh token deliberately gets the extension .txt: you should not mistake it for a badge that you show somewhere.

Step 2 – the visitor pass.

# on id1
step crypto jwt inspect --insecure < ~/kurs/09/anna-zugang.jwt

Expected (excerpt – the payload, signature omitted):

  "payload": {
    "exp": 1796219244,
    "iat": 1796218944,
    "auth_time": 1796218930,
    "jti": "onrtdg:5bd9203e-007d-21df-53f7-3bc036c569b8",
    "iss": "http://172.16.0.126:8080/realms/gebaeude",
    "aud": "account",
    "sub": "ebaf76a2-697c-40f3-910a-75e4d935cb6c",
    "typ": "Bearer",
    "azp": "ladenkasse-cli",
    "sid": "d3unt_BrIlLge_PNYwtU72ZJ",
    "acr": "1",
    "realm_access": {
      "roles": [
        "offline_access",
        "uma_authorization",
        "default-roles-gebaeude"
      ]
    },
    "resource_access": {
      "account": {
        "roles": [
          "manage-account",
          "manage-account-links",
          "view-profile"
        ]
      }
    },
    "scope": "openid profile email",
    "email_verified": true,
    "name": "Anna Berger",
    "preferred_username": "anna",
    "given_name": "Anna",
    "family_name": "Berger",
    "email": "[email protected]"
  },
Field Value Meaning
iss …/realms/gebaeude issued by the building’s reception
sub ebaf76a2-… Anna’s user ID from Drill 1 – not her name
aud account which door: Keycloak’s own account management, because of the roles under resource_access
azp ladenkasse-cli “authorized party”: which program requested the token
typ Bearer an access token: whoever has it may use it
iat, exp 13:42:24, 13:47:24 UTC exactly 300 seconds
auth_time 13:42:10 UTC when Anna entered her password – 14 seconds before collection
sid d3unt_… session, equal to session_state from Drill 3
scope openid profile email the access areas
realm_access.roles three default roles what Anna may do in the realm; she has no roles of her own yet

What you see: The same token contains two identities: who (Anna, sub) and through which program (azp). This separation becomes crucial from Day 10, when an AI agent asks instead of the till.

Step 3 – the business card.

# on id1
step crypto jwt inspect --insecure < ~/kurs/09/anna-id.jwt

Expected (excerpt – only the fields that differ from the access token):

    "jti": "9d0467e8-9913-17a4-cd28-d6b63bdff000",
    "aud": "ladenkasse-cli",
    "typ": "ID",
    "at_hash": "892SDudjybCff9Iz09nU5Q",

What you see: The business card is addressed to the till (aud: ladenkasse-cli), has the type ID, no roles and no scope. at_hash is a fingerprint of the access token that was issued together with it – this way the till can check that both belong together.

Step 4 – the claim ticket.

# on id1
step crypto jwt inspect --insecure < ~/kurs/09/anna-erneuern.txt

Expected:

{
  "header": {
    "alg": "HS512",
    "kid": "723b4f04-4f7b-40b2-8d98-5c0470d3b4e7",
    "typ": "JWT"
  },
  "payload": {
    "exp": 1796220744,
    "iat": 1796218944,
    "jti": "ff3b16c0-b894-106c-f05d-e3f992634469",
    "iss": "http://172.16.0.126:8080/realms/gebaeude",
    "aud": "http://172.16.0.126:8080/realms/gebaeude",
    "sub": "ebaf76a2-697c-40f3-910a-75e4d935cb6c",
    "typ": "Refresh",
    "azp": "ladenkasse-cli",
    "sid": "d3unt_BrIlLge_PNYwtU72ZJ",
    "scope": "openid profile roles web-origins acr basic email",
    "aud_x": "account",
    "prov": "default"
  },
  "signature": "Z8bMUWAAaDkO0kbXWs-UMEpLnSgBKgsjZ0BdK_zDIj9F9F1jD98tkYoxNjBKcsmofaWWg42tr1MKNWlgPu1eEg"
}

What you see: Three differences from the other two:

  • alg: HS512 instead of RS256. HS512 is a symmetric algorithm: the same secret key signs and verifies. It is not in any JWKS. Only Keycloak itself can verify this ticket – exactly right for a claim ticket that is only worth something at reception.
  • aud is the realm itself. No service should accept it.
  • exp - iat = 1800 seconds: half an hour during which the till can get new visitor passes.

That Keycloak issues the refresh token as a JWT is a Keycloak peculiarity. Other issuers issue an opaque string. A program must not rely on either and simply passes it on.

Step 5 – show the pass at a door. The nearest door is the userinfo_endpoint from Drill 3: it accepts an access token and returns whom it belongs to. curl can read a header from a file. You build that file with a jq that puts the text Authorization: Bearer in front of the token:

# on id1
jq -r '"Authorization: Bearer " + .access_token' ~/kurs/09/anmeldung.json > ~/kurs/09/kopf-zugang.txt
  • "Authorization: Bearer " + .access_token concatenates the fixed text with the token.
  • -r outputs the result without quotes.
# on id1
curl -s http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/userinfo -H @$HOME/kurs/09/kopf-zugang.txt
  • -H @datei reads the headers from the file.

Expected:

{"sub":"ebaf76a2-697c-40f3-910a-75e4d935cb6c","email_verified":true,"name":"Anna Berger","preferred_username":"anna","given_name":"Anna","family_name":"Berger","email":"[email protected]"}

What you see: The door accepted the pass and names Anna.

Step 6 – the business card at the same door. A second header file with the ID token:

# on id1
jq -r '"Authorization: Bearer " + .id_token' ~/kurs/09/anmeldung.json > ~/kurs/09/kopf-id.txt
# on id1
curl -s -i http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/userinfo -H @$HOME/kurs/09/kopf-id.txt
  • -i also shows the response headers; that is where the reason is.

Expected (excerpt):

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="gebaeude", error="invalid_token", error_description="Token verification failed"

What you see: The same seal, the same issuer, the same Anna – and still rejected. The business card is not a visitor pass (typ: ID, addressed to the till). Programs that send an ID token to an API are a classic mistake.

Remember: The business card tells the till who is there. Only the visitor pass opens doors. Only reception sees the claim ticket.

Save your progress? Sign up for free

Drill 5: Access areas

Where you are: on id1 and in the browser.

What you have afterwards: two scopes of your own, one of which the till may ask for, and a token with lager:lesen.

Later the warehouse should accept only visitor passes that say lager:lesen. In Keycloak you create scopes as a client scope and attach them to a client.

Step 1 – create the scope lager:lesen.

# on id1
/opt/keycloak/bin/kcadm.sh create client-scopes -r gebaeude -s name=lager:lesen -s protocol=openid-connect -s 'attributes."include.in.token.scope"=true' -s 'attributes."display.on.consent.screen"=false'
Option Value Meaning
create client-scopes create a new scope
-s name= lager:lesen this is how it appears later in the scope field
-s protocol= openid-connect for OIDC tokens (not SAML)
-s 'attributes."include.in.token.scope"=' true the name appears in the token’s scope field
-s 'attributes."display.on.consent.screen"=' false do not display on the consent page

Expected:

Created new client-scope with id '41ee786f-a7c2-40f3-bc99-0eb752ea480a'

Step 2 – attach it to the till as an optional scope. The paths contain the client ID from Drill 2 and the scope ID from step 1 – use your own:

# on id1
/opt/keycloak/bin/kcadm.sh update clients/cd9ee231-02bd-467c-82e8-d2c8b57ca8de/optional-client-scopes/41ee786f-a7c2-40f3-bc99-0eb752ea480a -r gebaeude
  • update clients/<client-id>/optional-client-scopes/<scope-id> attaches the scope as optional.

No output.

# on id1
/opt/keycloak/bin/kcadm.sh get clients/cd9ee231-02bd-467c-82e8-d2c8b57ca8de/optional-client-scopes -r gebaeude --fields name

Expected:

[ {
  "name" : "address"
}, {
  "name" : "phone"
}, {
  "name" : "organization"
}, {
  "name" : "offline_access"
}, {
  "name" : "lager:lesen"
}, {
  "name" : "microprofile-jwt"
} ]

Step 3 – create the scope lager:schreiben, but do not attach it.

# on id1
/opt/keycloak/bin/kcadm.sh create client-scopes -r gebaeude -s name=lager:schreiben -s protocol=openid-connect -s 'attributes."include.in.token.scope"=true' -s 'attributes."display.on.consent.screen"=false'

Expected:

Created new client-scope with id '15701f7d-b3c6-4bcf-8a06-ea4a411dc384'

The scope now exists in the realm. The till has it neither as default nor as optional.

Step 4 – ask for more than you may. A new device sign-in that asks for both warehouse scopes:

# on id1
curl -s http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/auth/device -d client_id=ladenkasse-cli -d "scope=openid lager:lesen lager:schreiben" -o ~/kurs/09/geraet2.json -w "%{http_code}\n"
  • -d "scope=…" – several scopes separated by spaces; the quotes keep them together for the shell.

Expected:

400
# on id1
jq . ~/kurs/09/geraet2.json

Expected:

{
  "error": "invalid_scope",
  "error_description": "Invalid scopes: openid lager:lesen lager:schreiben"
}

What you see: Keycloak does not silently strip the disallowed scope; it rejects the whole request – even before Anna is asked. No person can approve something for a till that reception has not provided for that till.

Step 5 – only what is allowed.

# on id1
curl -s http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/auth/device -d client_id=ladenkasse-cli -d "scope=openid lager:lesen" -o ~/kurs/09/geraet2.json -w "%{http_code}\n"

Expected:

200
# on id1
jq . ~/kurs/09/geraet2.json

Expected (your codes will differ):

{
  "device_code": "Plse-THbCVLQDtm-iK1H6cXJhOk8Cg-oEl8OLWxU-wg",
  "user_code": "TKXU-RDEW",
  "verification_uri": "http://172.16.0.126:8080/realms/gebaeude/device",
  "verification_uri_complete": "http://172.16.0.126:8080/realms/gebaeude/device?user_code=TKXU-RDEW",
  "expires_in": 600,
  "interval": 5
}
# on id1
jq -r .device_code ~/kurs/09/geraet2.json > ~/kurs/09/geraet2-code.txt

Step 6 – Anna gives consent again. Enter the new queue number in the browser. In the lab the sign-in page with password appeared again, followed by the same consent page as in Drill 3 – with three items, without “read warehouse”. That is due to display.on.consent.screen=false from step 1. Confirm with Yes.

Step 7 – collect and read.

# on id1
curl -s http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/token -d client_id=ladenkasse-cli -d grant_type=urn:ietf:params:oauth:grant-type:device_code --data-urlencode device_code@$HOME/kurs/09/geraet2-code.txt -o ~/kurs/09/anmeldung2.json -w "%{http_code}\n"

Expected:

200
# on id1
jq -r .access_token ~/kurs/09/anmeldung2.json > ~/kurs/09/anna-lesen.jwt
# on id1
step crypto jwt inspect --insecure < ~/kurs/09/anna-lesen.jwt

Expected (excerpt – look for scope and sid):

    "sid": "GNWtcvXAmWHb793fvwflySpN",
    "scope": "openid profile email lager:lesen",

What you see: lager:lesen is now on the pass. The sid is different from Drill 4: every device sign-in created its own session. Anna is now in the visitor log twice.

Remember: The till always gets default scopes, optional ones only on request, all others never. Anna has approved a scope even if nobody sees it – so display important scopes on the consent page.

Save your progress? Sign up for free

Diagnosis task

Five minutes after Drill 4 the till reports: “Anna has been signed out, the door no longer accepts the pass.” The same command as in Drill 4, step 5, only with -i:

# on id1
curl -s -i http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/userinfo -H @$HOME/kurs/09/kopf-zugang.txt

Expected (excerpt):

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="gebaeude", error="invalid_token", error_description="Token verification failed"

The same message as with the business card in Drill 4. Does Anna really have to go back to reception?

Solution path:

  1. Token verification failed only says that the check failed. Keycloak writes the reason to its log:

    # on id1
    sudo journalctl -u keycloak --since "-10 min" --grep "error=" --no-pager
    • --since "-10 min" – only the last ten minutes.
    • --grep "error=" – only lines with an error field.
    • --no-pager – print everything at once.

    Expected (excerpt, wrapped – the two USER_INFO_REQUEST_ERROR lines):

    13:42:45 … type="USER_INFO_REQUEST_ERROR", realmName="gebaeude", clientId="null", userId="null",
      ipAddress="172.16.0.126", error="invalid_token",
      reason="Token type is incorrect. Expected '[Bearer, DPoP]' but was 'ID'", …
    13:47:52 … type="USER_INFO_REQUEST_ERROR", realmName="gebaeude", clientId="null", userId="null",
      ipAddress="172.16.0.126", error="invalid_token", reason="Token is not active", …

    The first line is the business card from Drill 4. The second is the till now: Token is not active – expired.

  2. Cross-check on the token itself:

    # on id1
    step crypto jwt inspect --insecure < ~/kurs/09/anna-zugang.jwt

    Expected (excerpt): "exp": 1796219244 – that is 13:47:24 UTC. Compare with the clock:

    # on id1
    date -u +%s

    Expected (your number will differ):

    1796219273

    29 seconds after exp. The visitor pass did what it is supposed to do: it is worthless after five minutes.

  3. Anna does not have to go back to reception. The till has the claim ticket. It exchanges it for a new visitor pass:

    # on id1
    curl -s http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/token -d client_id=ladenkasse-cli -d grant_type=refresh_token --data-urlencode refresh_token@$HOME/kurs/09/anna-erneuern.txt -o ~/kurs/09/erneuert.json -w "%{http_code}\n"
    • -d grant_type=refresh_token – “I am redeeming a claim ticket”.
    • --data-urlencode refresh_token@… – the claim ticket from Drill 4.

    Expected:

    200
    # on id1
    jq 'del(.access_token, .id_token, .refresh_token)' ~/kurs/09/erneuert.json

    Expected:

    {
      "expires_in": 300,
      "refresh_expires_in": 1800,
      "token_type": "Bearer",
      "not-before-policy": 0,
      "session_state": "d3unt_BrIlLge_PNYwtU72ZJ",
      "scope": "openid profile email"
    }

    The same session (session_state), new tokens, again 300 seconds.

  4. New header file, new attempt:

    # on id1
    jq -r '"Authorization: Bearer " + .access_token' ~/kurs/09/erneuert.json > ~/kurs/09/kopf-zugang.txt
    # on id1
    curl -s http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/userinfo -H @$HOME/kurs/09/kopf-zugang.txt

    Expected:

    {"sub":"ebaf76a2-697c-40f3-910a-75e4d935cb6c","email_verified":true,"name":"Anna Berger","preferred_username":"anna","given_name":"Anna","family_name":"Berger","email":"[email protected]"}
  5. One final observation. Redeem the old claim ticket once more:

    # on id1
    curl -s http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/token -d client_id=ladenkasse-cli -d grant_type=refresh_token --data-urlencode refresh_token@$HOME/kurs/09/anna-erneuern.txt -w "\n%{http_code}\n"

    Expected (excerpt – tokens shortened, the last line is the status):

    {"access_token":"eyJhbGciOiJSUzI1NiIsInR5…","expires_in":300,"refresh_expires_in":1800,…
    200

    It is still valid. By default, Keycloak accepts a claim ticket as often as you like until it expires. Whoever steals a claim ticket can use it for half an hour to get visitor passes alongside the real till – the enterprise note shows how to turn that off.

The lesson: with short tokens, a 401 after a few minutes is not an error but the normal case. A program renews the access token itself instead of sending the person back to reception. And the door does not reveal the reason for a rejection – only the issuer’s log does.

Challenge

Anna is leaving the company. As an administrator, end all of her sessions. What then happens to the access token from the diagnosis task, which is still valid for a few minutes – at the userinfo door, at a service that verifies tokens only with the JWKS, and at the next refresh? Write down the commands before you read the solution. You have to hurry: the access token is valid for only five minutes.

Solution:

First the visitor log – the two sessions from Drill 4 and Drill 5:

# on id1
/opt/keycloak/bin/kcadm.sh get users/ebaf76a2-697c-40f3-910a-75e4d935cb6c/sessions -r gebaeude

Expected (excerpt – two entries, the address is that of your browser machine):

[ {
  "id" : "GNWtcvXAmWHb793fvwflySpN",
  "username" : "anna",
  "ipAddress" : "172.16.0.31",
  "clients" : {
    "cd9ee231-02bd-467c-82e8-d2c8b57ca8de" : "ladenkasse-cli"
  },
}, {
  "id" : "d3unt_BrIlLge_PNYwtU72ZJ",
  "username" : "anna",
  "ipAddress" : "172.16.0.31",

For later, the current access token and the current claim ticket as files:

# on id1
jq -r .access_token ~/kurs/09/erneuert.json > ~/kurs/09/anna-zugang2.jwt
# on id1
jq -r .refresh_token ~/kurs/09/erneuert.json > ~/kurs/09/anna-erneuern2.txt

End all sessions:

# on id1
/opt/keycloak/bin/kcadm.sh create users/ebaf76a2-697c-40f3-910a-75e4d935cb6c/logout -r gebaeude
  • create users/<id>/logout signs the user out everywhere. No output.
# on id1
/opt/keycloak/bin/kcadm.sh get users/ebaf76a2-697c-40f3-910a-75e4d935cb6c/sessions -r gebaeude

Expected:

[ ]

The userinfo door:

# on id1
curl -s -i http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/userinfo -H @$HOME/kurs/09/kopf-zugang.txt

Expected (excerpt):

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="gebaeude", error="invalid_token", error_description="user_session_not_found"

This door belongs to Keycloak and looks in the visitor log. The session is gone, so the request is rejected.

The claim ticket:

# on id1
curl -s http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/token -d client_id=ladenkasse-cli -d grant_type=refresh_token --data-urlencode refresh_token@$HOME/kurs/09/anna-erneuern2.txt -w "\n%{http_code}\n"

Expected:

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

Reception looks in the visitor log too. From now on there are no new visitor passes.

A service that only checks the seal: It loads the specimen card (JWKS) once and then verifies without asking back – like the warehouse from Day 12 on:

# on id1
curl -s http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/certs -o ~/kurs/09/gebaeude.jwks -w "%{http_code}\n"

Expected:

200
# on id1
step crypto jwt verify --jwks ~/kurs/09/gebaeude.jwks --iss http://172.16.0.126:8080/realms/gebaeude --aud account < ~/kurs/09/anna-zugang2.jwt
  • --jwks – the specimen card as a file.
  • --iss and --aud – which issuer and which door are expected.

Expected (excerpt – the check passes, the token is printed):

    "exp": 1796219574,
    "iat": 1796219274,
    "auth_time": 1796218930,
    "iss": "http://172.16.0.126:8080/realms/gebaeude",
    "aud": "account",
    "sub": "ebaf76a2-697c-40f3-910a-75e4d935cb6c",
    "typ": "Bearer",
    "azp": "ladenkasse-cli",
    "sid": "d3unt_BrIlLge_PNYwtU72ZJ",

In the lab this ran at 13:48:43, twenty seconds after the sign-out. The seal is genuine, the lifetime is not over yet – the service lets Anna in until exp is reached (here 13:52:54).

What you see: Signing out takes effect immediately wherever someone looks in the visitor log, and nowhere else. A self-contained token cannot be recalled; it can only expire. That is exactly why the visitor pass is valid for five minutes and not for a day. How to close the window when five minutes is too long is the topic of Day 14.

Save your progress? Sign up for free

Checkpoint

# on id1
/opt/keycloak/bin/kcadm.sh get users -r gebaeude --fields username,enabled

Expected:

[ {
  "username" : "anna",
  "enabled" : true
} ]
# on id1
/opt/keycloak/bin/kcadm.sh get clients/cd9ee231-02bd-467c-82e8-d2c8b57ca8de/optional-client-scopes -r gebaeude --fields name

Expected (excerpt): an entry "name" : "lager:lesen" next to the five standard scopes.

# on id1
curl -s http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/auth/device -d client_id=ladenkasse-cli -d "scope=openid lager:lesen" -w "\n%{http_code}\n"

Expected (your codes will differ):

{"device_code":"c5ZZPy4b80n78gBmRM2VDUdxtSGQzaq4r9mgrCVAc9Y","user_code":"OKUI-MXTG","verification_uri":"http://172.16.0.126:8080/realms/gebaeude/device","verification_uri_complete":"http://172.16.0.126:8080/realms/gebaeude/device?user_code=OKUI-MXTG","expires_in":600,"interval":5}
200

Simply let this process lapse; after ten minutes it is gone.

Test yourself

  1. Why is ladenkasse-cli a public client, and what does Keycloak lose because of that?
  2. The till shows Anna the user_code, never the device_code. What could someone do with a photographed device_code, and why only briefly?
  3. A program sends the ID token to an API and gets 401. How can you tell from the token that it is the wrong one?
  4. Anna’s access token contains sub and azp. What does each of them say, and why do you need both from Day 10 on?
  5. What happens if the till asks for a scope it has neither as default nor as optional?
  6. Why can no service other than Keycloak verify the refresh token, and why is that intended?

Answers:

  1. It runs on people’s machines; a secret in it would be readable by anyone. So Keycloak cannot verify which program is asking – anyone can call themselves ladenkasse-cli. The protection comes from Anna’s consent in the browser.
  2. They could collect the tokens as soon as Anna has given consent – that is, steal Anna’s sign-in. But the code is valid for only ten minutes (expires_in) and only a single time (Drill 3, step 8: Device code not valid).
  3. typ is ID instead of Bearer, and aud is the client (ladenkasse-cli), not the service.
  4. sub is the person (Anna’s user ID), azp the program that requested the token. When an AI agent acts for Anna, a service must see both: on whose behalf, and who is actually asking.
  5. Keycloak rejects the whole request with invalid_scope before Anna is asked.
  6. It is signed with HS512, a symmetric key that exists only in Keycloak and is not in any JWKS, and its aud is the realm itself. A claim ticket should not be worth anything anywhere else.

Interview note

“How does a person sign in to a command-line tool without typing their password?” – Good answer: with the Device Authorization Grant (RFC 8628). The tool is a public client without a secret; it gets a device_code and a short user_code, the person enters the user_code in the browser at the identity provider, signs in there and gives consent. The tool polls the token endpoint at the given interval, respects authorization_pending and slow_down, and then receives ID, access and refresh tokens. Only the IdP sees the password; MFA and policies take effect there. Important in the answer: the ID token is for the client, the access token for the API; a client cannot get scopes that have not been assigned to it.

Enterprise note

In a company, Keycloak (or another IdP) is connected to the directory service, and people sign in with MFA. There, the device sign-in is the method of choice for command-line tools on servers and for devices without a keyboard. These points belong in every approval:

  • Phishing: An attacker can start a device sign-in themselves and send a victim the user_code with “please confirm here”. The consent page must therefore clearly show which program gets access, and employees must know that they should only enter codes they have just triggered themselves. Some organizations allow the grant only for a list of known clients.
  • Scopes as a contract: Create business scopes (lager:lesen) centrally, attach them deliberately as optional, and show everything that writes or costs money on the consent page.
  • Claim tickets only once: In the lab, the realm is set to "revokeRefreshToken" : false and "refreshTokenMaxReuse" : 0 (queried with kcadm.sh get realms/gebaeude --fields revokeRefreshToken,refreshTokenMaxReuse). With revokeRefreshToken=true, every refresh token is used up when redeemed, and the program has to keep the new one each time. If an old one shows up again, that indicates theft. This course keeps the default so that the agents stay simple from Day 10 on.
  • Session duration: ssoSessionIdleTimeout (1800 s in the lab) and ssoSessionMaxLifespan (36000 s) limit how long a till can keep working without a new sign-in.

Summary

  • Anna has an account in the realm gebaeude; kcadm.sh prompted for the password, it was not on the command line.
  • ladenkasse-cli is a public client without a secret that may only use the device sign-in.
  • Device sign-in: device_code for the device, user_code for the person, ten minutes, authorization_pending and slow_down while polling, the device_code is valid once.
  • Three tokens: ID token to the client, access token to a service (typ: Bearer, 300 s), refresh token to Keycloak itself (HS512, 1800 s).
  • sub is the person, azp the program.
  • Scopes: default always, optional on request, everything else invalid_scope.
  • Expired access token: 401 at the door, Token is not active in the Keycloak log; the till gets a new one with grant_type=refresh_token without disturbing Anna. Out of the box, Keycloak accepts the same claim ticket several times.
  • Signing out ends sessions: userinfo and refresh fail immediately, while a service that only does JWKS verification keeps accepting the access token until exp.

Commands at a glance

Command What for
kcadm.sh create users -r <realm> -s username=… -s enabled=true create a user
kcadm.sh set-password -r <realm> --username <name> set a password (prompted)
kcadm.sh create clients -r <realm> -s clientId=… -s publicClient=true … create a public client
kcadm.sh create client-scopes -r <realm> -s name=… -s protocol=openid-connect create a scope
kcadm.sh update clients/<id>/optional-client-scopes/<scope-id> -r <realm> attach a scope as optional
curl … /protocol/openid-connect/auth/device -d client_id=… -d scope=… start a device sign-in
curl … /protocol/openid-connect/token -d grant_type=urn:ietf:params:oauth:grant-type:device_code --data-urlencode device_code@<datei> collect tokens
jq -r '"Authorization: Bearer " + .access_token' <datei> > kopf.txt build a header for curl -H @kopf.txt
curl … /protocol/openid-connect/userinfo -H @kopf.txt whom does this access token belong to
step crypto jwt inspect --insecure < <datei> read a token without verifying it

Contents

More