ai newsDi., 1. Dez.
EilmeldungThe Model Proposes, Your Code Disposes: A Tool-Calling Agent Loop for Android with Gemini Nano

Let an AI Agent Act for a User, With Consent: Token Exchange Delegation in Keycloak

Tested with Keycloak 26.8.2 and oauth2c 1.21.1 on macOS. An AI agent needs to read Alice's notes and file a summary for her. Somewhere in the setup, someone has to answer a simple question: what token does the agent use? The two usual answers are both bad. Hand the agent Alice's own access token, a

dev.toMontag 04:16 · 30.11.6 Min. Lesezeit
Bild: dev.to

Tested with Keycloak 26.8.2 and oauth2c 1.21.1 on macOS.

An AI agent needs to read Alice's notes and file a summary for her. Somewhere in the setup, someone has to answer a simple question: what token does the agent use?

The two usual answers are both bad. Hand the agent Alice's own access token, and every service it calls thinks Alice did it herself. Give the agent a service account that can read everyone's notes, and one prompt injection turns it into a very helpful insider.

OAuth Token Exchange ( RFC 8693 ) describes two ways one party can act for another:

Handing Alice's own token to the agent is worse than either: it's token passthrough, impersonation without even an authorization server in the loop to apply policy or keep a record. The Keycloak guide lists what goes wrong: no audience control, no scope restriction, no audit trail, and Alice is never asked ( Keycloak guide, 26.8.2 ).

Delegation comes in two flavors. Admin delegation ( delegation:user:<username> ) hands a token to a human administrator. Client delegation ( delegation:client:<client_id> ) hands it to an application, and that's the one built for agents. The rest of this post uses client delegation ( 26.8.0 release notes ).

token-exchange-delegation is a preview feature in Keycloak 26.8, and it builds on parameterized-scopes, also preview. Everything that has to line up:

Once the feature is on, Keycloak creates the delegation:user and delegation:client client scopes automatically, in every realm.

You need Docker, curl, python3 and oauth2c, a small command-line OAuth client that handles the browser login ( brew install oauth2c on macOS).

git clone https://github.com/Anoopgopi/keycloak-token-exchange-delegation-demo.git cd keycloak-token-exchange-delegation-demo./scripts/run-all.sh Enter fullscreen mode Exit fullscreen mode run-all.sh starts Keycloak in a local container and runs every step below for you. A browser opens twice; log in as alice / alice. To follow along by hand instead, run docker compose up -d and./scripts/setup-realm.sh, then the commands in each step. To start over from scratch, run docker compose down -v first. A second run on the same container gives confusing results.

The Keycloak part of compose.yaml is short:

services: keycloak: image: quay.io/keycloak/keycloak:26.8.2 command: - start-dev # dev mode: local demo only - --features=token-exchange-delegation,parameterized-scopes environment: KC_BOOTSTRAP_ADMIN_USERNAME: admin KC_BOOTSTRAP_ADMIN_PASSWORD: admin ports: - "8080:8080" Enter fullscreen mode Exit fullscreen mode start-dev, plain HTTP and admin / admin are fine on a laptop and nowhere else.

setup-realm.sh creates a realm called demo with fine-grained admin permissions turned on, a user alice, and the two clients from the table. notes-app is a public client (no secret, like a browser or CLI app) with http://localhost:9876/callback as its redirect URI, which is where oauth2c listens. It's a handful of Admin REST calls, mirroring Keycloak's own delegation test. All output below is from Keycloak 26.8.2 in that container.

Alice logs in to notes-app and asks for the delegation scope. oauth2c runs the authorization code flow: a browser login, then a code swapped for tokens. --pkce adds a one-time secret so a stolen code is useless, which public clients need.

oauth2c http://localhost:8080/realms/demo \ --client-id notes-app --auth-method none --pkce \ --grant-type authorization_code --response-types code --response-mode query \ --redirect-url http://localhost:9876/callback \ --scopes openid,delegation:client:agent-bot \ --silent > alice.json python3 -c "import json;print(json.load(open('alice.json'))['access_token'])" | python3 scripts/decode-jwt.py Enter fullscreen mode Exit fullscreen mode decode-jwt.py (in the repo) prints the claims that matter. You can also paste the token into any JWT decoder. Here's what came back:

{ "azp": "notes-app", "scope": "openid profile email" } Enter fullscreen mode Exit fullscreen mode Quick key: sub is who the token is about, azp is the client it was issued to, aud is the service it's meant for, and scope is what it may do.

The login worked, but the delegation scope is gone, and there's no aud and no may_act. Nothing complained. This is the one people miss. Without a permission saying agent-bot may act for this user, Keycloak drops the scope and carries on. The guide's troubleshooting table lists two more causes of the same symptom: a misspelled client ID, and an actor client without a service account.

The permission lives in FGAP v2 and takes two objects: a client policy that matches agent-bot, and a permission that gives that policy the delegate scope on Users. In the Admin Console, enable them under Realm Settings → Admin Permissions, then go to Admin Permissions, create a permission on the Users resource type with the delegate scope, and add a Client policy for agent-bot.

grant-delegation.sh does the same through the Admin REST API, with an admin token and the two client IDs it looks up first. The two calls, shortened:

# policy: "the caller is agent-bot" POST /admin/realms/demo/clients/ < admin-permissions-id > /authz/resource-server/policy/client { "name": "agent-bot may act", "clients": [ "<agent-bot-id>" ], "logic": "POSITIVE" } # permission: that policy may "delegate" for all users POST /admin/realms/demo/clients/ < admin-permissions-id > /authz/resource-server/permission/scope { "name": "agent-bot delegate for users", "resourceType": "Users", "scopes": [ "delegate" ], "policies": [ "agent-bot may act" ] } Enter fullscreen mode Exit fullscreen mode The demo grants it for all users. To limit it to some users, the guide uses a different permission: on the Groups resource type, with the delegate-members scope and Enforce access to: Specific groups.

Run the same oauth2c command from Step 1 again. This time Keycloak asks Alice before it issues anything:

ALICE_TOKEN = $( python3 -c "import json;print(json.load(open('alice.json'))['access_token'])" ) Enter fullscreen mode Exit fullscreen mode Decoded:

{ "sub": "e42820b7-…", "azp": "notes-app", "aud": "agent-bot", "scope": "openid delegation:client:agent-bot profile email", "may_act": { "sub": "6d370417-…", "client_id": "agent-bot" } } Enter fullscreen mode Exit fullscreen mode Two things changed. may_act says agent-bot may act for Alice; the sub inside it is the user ID of agent-bot's service account. And agent-bot was added to aud, because standard token exchange requires the requesting client to be in the subject token's audience.

First the agent gets its own token, using its client ID and secret. setup-realm.sh sets a throwaway demo secret (in the Admin Console it's under Clients → agent-bot → Credentials ):

AGENT_SECRET = agent-bot-local-demo-secret # local demo value from scripts/common.sh AGENT_TOKEN = $( curl -s http://localhost:8080/realms/demo/protocol/openid-connect/token \ -d grant_type = client_credentials -d client_id = agent-bot -d client_secret = "$AGENT_SECRET" \ | python3 -c "import sys,json;print(json.load(sys.stdin)['access_token'])" ) Enter fullscreen mode Exit fullscreen mode Then it sends both tokens to the token endpoint, Alice's as the subject and its own as the actor. Sending actor_token is what makes this a delegation request rather than a plain exchange:

curl -s http://localhost:8080/realms/demo/protocol/openid-connect/token \ -d grant_type = urn:ietf:params:oauth:grant-type:token-exchange \ -d client_id = agent-bot -d client_secret = "$AGENT_SECRET" \ -d subject_token = "$ALICE_TOKEN" \ -d subject_token_type = urn:ietf:params:oauth:token-type:access_token \ -d actor_token = "$AGENT_TOKEN" \ -d actor_token_type = urn:ietf:params:oauth:token-type:access_token Enter fullscreen mode Exit fullscreen mode The delegated token:

{ "sub": "e42820b7-…", "azp": "agent-bot", "aud": "account", "scope": "profile email", "act": { "sub": "6d370417-…", "client_id": "agent-bot" } } Enter fullscreen mode Exit fullscreen mode sub is still Alice, and act names the agent. The audience and scopes now come from agent-bot's configuration, not from Alice's token. Here aud is account only because agent-bot is a fresh client with Keycloak's default roles. In a real setup, give agent-bot an audience mapper for the notes API and remove what it doesn't need. The narrowing is only as tight as that configuration.

A good first experiment after the demo: add act logging to one real endpoint and see how often you'd want to say no to a delegated call.

Anoop Gopi is a senior technology leader and digital identity expert specializing in IAM, cybersecurity and cloud architecture. Views are his own.

Quelle: dev.to (dev.to). Original öffnen