Skip to content

Keycloak as the authorization server

This recipe configures Keycloak (tested against 26.x) as the authorization server for Kozou’s OAuth resource-server mode. Keycloak is the natural choice when you self-host identity or bridge a corporate directory.

The scope-and-mapper core of this recipe exists in runnable form: the Kozou repository’s end-to-end test suite drives a real Keycloak against keycloak-realm-e2e.json — a worked example of the client scopes, mappers, and role attributes (Steps 1, 2, and 4) you can diff your realm against. It is a test realm, not a full deployment: it authenticates with direct-access grants rather than the authorization-code flow, leaves dynamic client registration off (Step 5 is not represented in it), and imports with sslRequired: none for a containerized test network — leave TLS required in any real realm.

Put the audience, role, and username mappers on the mcp:describe / mcp:execute client scopes themselves — not on a separate “roles” scope, not on realm defaults.

The reason is a chain: Kozou advertises its scopes in the protected-resource metadata → MCP clients echo that list into their dynamic client registration → Keycloak grants a dynamically-registered client only the scopes named in its registration (plus an internally-added basic). Realm-default scopes are not applied to DCR clients. So the mcp:* scopes are the only scopes guaranteed to reach the client — and any claim that is not mapped on them never reaches the token.

If the role claim rides a separate scope, tokens arrive at Kozou without a role, and Kozou rejects them (there is no default role on this surface). Nothing errors on the Keycloak side; enforcement just never works. This placement rule is the single most common failure mode.

Create two client scopes, mcp:describe and mcp:execute (Admin console: Client scopes → Create; or import — see the fixture’s clientScopes array). On each of them, add three protocol mappers:

MapperTypeConfiguration
AudienceAudience (oidc-audience-mapper)Included custom audience = your resource URI, e.g. https://mcp.example.com/mcp. Add to access token.
RoleUser attribute (oidc-usermodel-attribute-mapper)User attribute = app_role, token claim name = role, type String, single-valued. Add to access token.
UsernameUser property (oidc-usermodel-property-mapper)Property username → claim preferred_username (optional, display only — Kozou’s enforcement reads the role claim).

Two of these deserve a word:

  • The audience mapper is not optional. Keycloak does not implement RFC 8707 resource indicators — a client sending resource= gets it silently ignored. The audience mapper is the supported way to stamp the resource URI into aud, and Kozou strictly requires it to match.
  • The role mapper reads a user attribute (app_role here) whose value is the PostgreSQL role name. This is the same scalar-role-claim model as enterprise SSO, relocated to where DCR clients can actually receive it.

Mark both scopes as included in the token scope, and give them consent-screen text — dynamically-registered clients require consent, so your users will read it.

Add mcp:describe and mcp:execute to the realm’s default optional client scopes (Client scopes → realm settings, or defaultOptionalClientScopes in an import). Optional is enough: clients request them by name. Without this, Keycloak’s registration policy refuses DCR requests that name them (“Requested scope not trusted”).

In kozou.config.yaml, set:

extraScopesSupported: [offline_access]

Clients that echo Kozou’s advertised scope list into their registration (Claude Code does) will then request offline_access, which Keycloak requires for refresh tokens. Without it, the registered client never holds the scope, and the authorization request — which asks for offline_access — fails wholesale with invalid_scope. The advertised list is “what clients should request”, not “what Kozou checks”; this is the canonical example.

First, make the realm keep app_role. Since Keycloak 24 the user profile is declarative, and by default a realm stores only the user attributes its profile declares; a new realm declares only username, email, firstName, and lastName. Until app_role is allowed, the admin console shows no Attributes tab on users to put it in, and the admin REST API accepts it, returns success, and silently discards it — the user comes back without it, and the role mapper has nothing to put in the token. In Realm settings, do one of these:

  • Declare the attribute (recommended): User profile → Create attribute, name app_role. Leave Who can edit? at admin only, the console’s default.
  • Or let administrators write undeclared attributes: General → Unmanaged Attributes = Only administrators can write. This also brings up an Attributes tab on each user.

Do not pick Enabled for Unmanaged Attributes. It lets each user rewrite their own attributes through the account REST API (/realms/<realm>/account), so a user can set their own app_role — and choose which PostgreSQL role they assume. Check the setting even if you never chose it: when Keycloak 24 migrated a realm that had not turned on the user profile, it set Unmanaged Attributes to Enabled. On such a realm app_role is already stored and the Attributes tab is already there, which makes this step look done.

Then set each user’s app_role to the PostgreSQL role they should assume (open the user under Users: the Details tab for a declared attribute, the Attributes tab for an unmanaged one; in the fixture, the users[].attributes block):

"attributes": { "app_role": ["app_viewer"] }

Read the user back before going further: with either setting above in place, app_role shows on the user, and if it does not, it was not stored. The fixture has no user-profile setting because a realm import stores the attribute without one.

This is an explicit admin action, by design. A user without the attribute authenticates fine but is rejected by Kozou — including every first-time user arriving through a federated IdP (Google, LDAP). Make role assignment part of your onboarding flow rather than working around it with a default.

Also confirm users hold the offline_access realm role — members of the realm’s default-roles-<realm> composite have it. Users created through the admin console do; users created by a realm import may not (imports don’t add the composite automatically — set realmRoles explicitly on imported users), and Keycloak then refuses to issue offline tokens with “Offline tokens not allowed for the user or client”.

Hosted MCP clients register themselves via anonymous DCR, which Keycloak’s Trusted Hosts policy refuses by default (403). The policy (Clients → Client registration → Anonymous access policies → Trusted Hosts) has two checks, and Keycloak requires every check that is on to pass. A new realm turns both on, and Keycloak will not save the policy with both off. Two ways to open it:

  • Match on redirect URIs (recommended): list the client callback hosts (for hosted clients, the claude.ai / ChatGPT callback hosts; for Claude Code, developers’ localhost) under Trusted Hosts, keep Client URIs Must Match on, and turn Host Sending Client Registration Request Must Match off. Left on, it also requires the connection to come from a trusted host’s address. A connection through Docker or a tunnel arrives from the gateway or tunnel daemon instead, and registration fails with 403 Policy 'Trusted Hosts' rejected request to client-registration service. Details: Host not trusted. (Claude Code reports Dynamic Client Registration rejected (HTTP 403)).
  • Match on the requesting host: keep Host Sending Client Registration Request Must Match on. Keycloak checks the connecting IP against the Trusted Hosts entries (a hostname entry is resolved to its address). Behind Docker or a tunnel, the connection arrives from the gateway or tunnel daemon, so the only address that can match is theirs — and every client behind them shares it.

If you would rather not open anonymous registration at all, pre-register a confidential client per tenant instead and skip DCR — see the deployment guide for why that is often the better hosted posture anyway.

Note that dynamically-registered clients are created with consent required — the first authorization shows a consent screen listing your scopes’ consent text (persistent, so once per user).

Realm imports don’t auto-create Keycloak’s built-in client scopes. Two resulting traps, both visible in the fixture:

  • DCR silently depends on a basic scope: Keycloak adds basic to every dynamically-registered client, and if the realm has no scope by that name, registration itself fails (“Requested scope ‘basic’ not trusted”) — confusingly, for a scope the client never asked for. Define a basic scope (the fixture gives it the sub and auth_time mappers) and put it in the realm’s default default-client-scopes.
  • sub is no longer automatic: since Keycloak 25 the sub claim rides the opt-in basic scope. The fixture’s basic includes an explicit sub mapper so tokens are self-contained.
  • offline_access may not be a trusted DCR scope: a console realm ships offline_access as a default optional client scope, so a dynamically-registered client can request it; a minimal import may omit it. Kozou advertises offline_access (Step 3) and clients request it, but Keycloak grants a DCR client only the scopes its registration policy trusts — so registration silently strips offline_access, and the authorization request then fails with invalid_scope. Keycloak’s error compounds the confusion by listing every requested scope (mcp:describe mcp:execute offline_access) as invalid, not just the missing one. Add offline_access to the realm’s default optional client scopes — the same place as the mcp:* scopes in Step 2.

A realm you created through the admin console has all of this already; only imports hit it.

server:
mcp:
http:
auth:
resource: https://mcp.example.com/mcp
authorizationServers:
- https://keycloak.example.com/realms/myrealm
jwt:
jwksUri: https://keycloak.example.com/realms/myrealm/protocol/openid-connect/certs
algorithms: [RS256]
roleClaim: role
allowedRoles: [app_viewer, app_editor]
extraScopesSupported: [offline_access]

Keycloak’s issuer is the realm URL without a trailing slash — exactly the authorizationServers entry above, which Kozou uses as the expected iss.

  1. curl https://mcp.example.com/.well-known/oauth-protected-resource — you should see your realm in authorization_servers and mcp:describe mcp:execute offline_access in scopes_supported.
  2. Connect a real client (Claude Code is the quickest: claude mcp add --transport http kozou https://mcp.example.com/mcp, then /mcp → authenticate). The browser flow should show your consent text.
  3. Watch Kozou’s stderr while the client connects (since v1.21.0). auth 401 no_token lines on their own are the normal start of a connection; any other auth line names the check that refused the token — the full list. With this recipe the usual ones are:
    • issuer_mismatch — the authorizationServers entry is not exactly the realm URL, without a trailing slash (Point Kozou at the realm).
    • audience_mismatch or audience_missing — the audience mapper is missing from the mcp:* scopes, or names something other than your resource URI (Step 1). Setting the top-level auth.jwt.audience does not help: that one belongs to the REST surface.
    • role_missing — either the user’s app_role was never stored (Step 4 — read the user back) or the role mapper is not on the mcp:* scopes (the one rule). In Claude Code it looks like this: claude mcp login reports success, and claude mcp list then shows the server as ! Needs authentication — Kozou refuses every request with 403, and its log names role_missing.
    • role_unreadable — the role mapper has Multivalued on, so role arrives as a list (Step 1 — single-valued).
  4. Negative check: a user without app_role must be rejected, not admitted with some default — Kozou logs auth 403 role_missing for the attempt.