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.
Keycloak 26.8 adds a third option, in preview: token exchange delegation. Alice approves the agent on a consent screen, and the agent gets a token that says "agent-bot, acting for Alice". This post walks through it on a laptop, with a demo repo you can run in about five minutes.
Whose name is on the token?
OAuth Token Exchange (RFC 8693) describes two ways one party can act for another:
- Impersonation. The agent gets a token that simply says "Alice". The notes service can't tell Alice and the agent apart.
- Delegation. The token still says "Alice" in
sub, and anact(actor) claim adds "agent-bot". The notes service sees both names and can log or refuse what the agent does.
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).
What Keycloak 26.8 adds
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:
| Piece | Setting | Why |
|---|---|---|
| Server | --features=token-exchange-delegation,parameterized-scopes | Both are preview, so off by default |
The user's app (notes-app) | Consent required on | Delegation scopes are only granted with consent. Without it, the login fails with invalid_scope |
The agent (agent-bot) | Confidential client, service account on (a built-in user that represents the client), Standard token exchange on | Requirements for the actor client |
| Permission | Fine-grained admin permissions v2 (FGAP: Keycloak's built-in way to say who may do what to which users), scope delegate | Decides which agents may act for which users |
Once the feature is on, Keycloak creates the delegation:user and delegation:client client scopes automatically, in every realm.
Try it: five minutes on a laptop
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 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" 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.
Step 1: the gotcha, before granting anything
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 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" } 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.
Step 2: allow agent-bot to act for users
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"]} 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.
Step 3: Alice says yes
Run the same oauth2c command from Step 1 again. This time Keycloak asks Alice before it issues anything:
The delegation consent isn't stored. Save Alice's new token for the next step:
ALICE_TOKEN=$(python3 -c "import json;print(json.load(open('alice.json'))['access_token'])") 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" } } 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.
Step 4: the agent exchanges
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'])") 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 The delegated token:
{ "sub": "e42820b7-…", "azp": "agent-bot", "aud": "account", "scope": "profile email", "act": { "sub": "6d370417-…", "client_id": "agent-bot" } } 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.
| Claim | Alice, no permission | Alice, after consent | Delegated token |
|---|---|---|---|
sub | Alice | Alice | Alice |
azp | notes-app | notes-app | agent-bot |
aud | (none) | agent-bot | account |
scope | openid profile email | + delegation:client:agent-bot | profile email |
may_act | (none) | agent-bot | (none) |
act | (none) | (none) | agent-bot |
What the delegated token can't do
checks.sh pokes at the edges:
- No refresh token. The exchange response has
access_token,expires_inandscope, and norefresh_token. The token lives in a transient session, a short-lived one that isn't stored. - No outliving Alice. The delegated token's
expwas identical to theexpof Alice's token. With Keycloak's default access token lifespan of 5 minutes, the agent holds the delegation for minutes, not days. An Advanced client switch can change that; keep it off. - No Admin API. Calling
/admin/realms/demo/userswith the delegated token returned401. Client delegation doesn't grant Admin API access, even though agent-bot has a service account. - No stripping the actor. Feeding the delegated token back into a standard exchange, without an actor, fails with
invalid_request: "Subject token with a delegation claim is not allowed for standard token exchange". That stops an agent from trading a delegated token for a plain one that no longer says who's acting.
How this lines up with RFC 8693
Closely, with a few Keycloak-specific choices on top. RFC 8693 itself says nothing about consent or admin permissions:
-
may_act, thenact. In RFC 8693 terms,may_act(§4.4) is a statement in the subject token that a party is allowed to become the actor.act(§4.1) records in the issued token who is acting. Keycloak only validatessub,client_idandissinsidemay_act. Any extra claims added through mappers on thedelegation:clientscope are copied intoactfor description only, never used to decide anything. - Two checks have to pass. Alice's consent, and an admin-defined FGAP permission. Consent alone isn't enough, so an admin decides which agents are eligible at all.
- Least privilege by construction. The delegated token takes the actor's audience and scopes, so the agent can't borrow reach that
notes-apphad. Note what it isn't: consent is a yes/no on the actor, not a list of scopes, and the result isn't an intersection with Alice's rights. - What each limit is for. No refresh token and the capped
expshrink the window for a stolen delegated token. Requiring the agent's own credentials means a stolen Alice token alone can't be exchanged. These are still bearer tokens, though: nothing here ties them to the agent's key, which is why the DPoP item below matters. - Stray
may_actclaims. A mapper could putmay_actinto a token outside the delegation scopes. The guide'smay-actclient policy executor re-validates anymay_actclaim in a token response. Add it under Realm settings → Client policies. - The API still has work to do. A token with
actonly helps if the resource server reads it: log the actor, and refuse delegated calls for high-risk operations such as deleting data.
Where it stops (as of 26.8)
- It's preview. Names and behavior can still change between releases, and preview features aren't fully supported yet.
- It doesn't stop prompt injection. If a poisoned note steers the agent, delegation limits what it can reach and records that agent-bot did it. It doesn't prevent the attack. Pair it with limits in the API.
- The actor is the client, not the agent run.
act.subis agent-bot's service account. Every instance and session of the agent shares that identity and one secret, so tracing a single agent run needs your own correlation IDs. - The handoff is yours. In the demo, a script passes Alice's token to the agent. In production,
notes-apphands a bearer token to the agent, and that handoff is a trust boundary to protect. - Consent is broad and repeated. The screen says "Allow agent-bot to act on your behalf?", with no purpose, data scope or duration. It isn't stored, so a long-running agent needs Alice to log in again.
- One hop only. An agent can't hand its delegated token to a second agent yet. Multi-hop chaining is tracked in #53040, with an open PR, #53285.
- DPoP-bound subject tokens. Allowing delegation of a DPoP-bound
subject_token(a token tied to the client's key, RFC 9449) by the client named inmay_actis an open enhancement: #55593. - Reserved claim names. Treating
actandmay_actas reserved claim names is tracked in #53039.
Where to start
- Turn on
token-exchange-delegationandparameterized-scopesin a test realm, not production. - Make the user-facing client Consent required, and give each agent its own confidential client with a service account and no admin roles.
- Grant delegation with FGAP v2 to specific agents, for specific groups (
delegate-members) rather than all users where you can, and add themay-actclient policy executor. - Give each agent client an explicit audience for the APIs it calls, and teach those APIs to log
act. - Run the demo repo and change one thing at a time. The silent drop is much easier to recognize once you've seen it on purpose.
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.
References
- Keycloak guide, Token exchange (delegation section), 26.8.2: https://github.com/keycloak/keycloak/blob/26.8.2/docs/guides/securing-apps/token-exchange.adoc
- Keycloak 26.8.0 release notes: https://github.com/keycloak/keycloak/blob/26.8.2/docs/documentation/release_notes/topics/26_8_0.adoc
- Keycloak delegation test (upstream): https://github.com/keycloak/keycloak/blob/main/tests/base/src/test/java/org/keycloak/tests/oauth/tokenexchange/ClientDelegationTest.java
- RFC 8693, OAuth 2.0 Token Exchange: https://datatracker.ietf.org/doc/html/rfc8693
- RFC 9449, OAuth 2.0 Demonstrating Proof of Possession (DPoP): https://datatracker.ietf.org/doc/html/rfc9449
- Demo repo: https://github.com/Anoopgopi/keycloak-token-exchange-delegation-demo
- oauth2c: https://github.com/cloudentity/oauth2c
Anoop Gopi is a senior technology leader and digital identity expert specializing in IAM, cybersecurity and cloud architecture. Views are his own.




