Securing AI agents with Keycloak and MCP: mTLS and DPoP-bound tokens

In short
  • Each AI agent is a Keycloak client that authenticates with a certificate (mTLS), so there's no client secret or API key to leak.
  • Every token it gets is DPoP-bound to a key the agent holds, scoped to one MCP server and only the tools it needs.
  • The MCP server checks the certificate first, then the token, the proof, the audience and each tool's scope. A leaked agent token gets an attacker nothing.

Why agents need this

Most agents run on an API key in their config and a bearer token that ends up in logs, traces and even tool output. One prompt injection that gets the agent to print its token, and someone else is your agent.

Typical agent setupWith mTLS + DPoP
A client secret or API key in the agent's configNo secret: the agent's certificate is its credential
A bearer token anyone can replay once it leaksA token alone gets a 401: every call needs a proof from the agent's key
One token that works on every MCP server and toolAudience = one MCP server; scopes per tool
Anything that can reach the MCP server can try its luckOnly agents with a certificate from your CA get in at all

This puts the two previous guides together: mTLS client authentication for who the agent is, and DPoP for binding every token to its key.

Step 1: Agent identities: certificates, not secrets

Our CA signs one certificate per agent, and the common name is the agent's identity (its Keycloak client ID). For the demo there's also a rogue agent: it claims to be notes-agent, but its certificate comes from a CA nobody trusts. In production, use real workload identity: SPIFFE/SPIRE, cert-manager or a cloud CA, with short-lived certificates.

for name in notes-agent support-agent; do
  openssl req -newkey rsa:2048 -nodes -subj "/CN=$name/O=Acme" -keyout $name.key -out $name.csr
  openssl x509 -req -in $name.csr -CA ca.crt -CAkey ca.key -CAcreateserial -days 365 -out $name.crt \
    -extfile <(printf "extendedKeyUsage=clientAuth")
done

Keycloak runs with HTTPS and KC_HTTPS_CLIENT_AUTH=request, checking client certificates against a truststore with our CA, exactly as in the mTLS guide.

Step 2: Keycloak: one client per agent

Each permission is a client scope, and each scope puts the MCP server in the token's audience, so a token only works on the server it's meant for:

MCP=https://localhost:9444/mcp
for scope in notes:read notes:write; do
  id=$(kcadm create client-scopes -r acme -s name=$scope -s protocol=openid-connect \
    -s 'attributes."include.in.token.scope"=true' -i)
  kcadm create client-scopes/$id/protocol-mappers/models -r acme -s name=mcp-audience \
    -s protocol=openid-connect -s protocolMapper=oidc-audience-mapper \
    -s "config.\"included.custom.audience\"=$MCP" -s 'config."access.token.claim"=true'
done

Each agent logs in with its certificate, gets DPoP-bound tokens, and only the scopes it needs:

kcadm create clients -r acme -s clientId=notes-agent -s publicClient=false -s serviceAccountsEnabled=true \
  -s standardFlowEnabled=false -s directAccessGrantsEnabled=false \
  -s clientAuthenticatorType=client-x509 \
  -s 'attributes."x509.subjectdn"=(.*, )?CN=notes-agent(, .*)?' \
  -s 'attributes."x509.allow.regex.pattern.comparison"=true' \
  -s 'attributes."dpop.bound.access.tokens"=true' \
  -s 'defaultClientScopes=["basic","notes:read"]'

Least privilege: notes-agent gets notes:read and nothing else, and support-agent gets no notes access at all. Keep basic in the list, or the token loses its sub claim.

In the admin console it's the client's Credentials tab (X509 Certificate and the subject pattern), Client scopes (just basic and notes:read), and Settings → Capability config → Require DPoP bound tokens.

Step 3: The MCP server: mTLS, then DPoP

The MCP server follows the MCP authorization spec, and checks who is connecting before it looks at a token:

StepCheckOn failure
1Client certificate signed by our CA403 untrusted_client
2Serves protected resource metadata (RFC 9728): Keycloak as the authorization server, DPoP required
3Authorization: DPoP with a valid Keycloak token whose aud is this MCP server401, pointing at the metadata
4A fresh DPoP proof from the key the token is bound to (cnf.jkt)401
5The token's azp is the agent named in this connection's certificate401
6Each tool checks its scope: list_notes needs notes:read, delete_note needs notes:writeinsufficient_scope

The metadata the server publishes:

{
  "resource": "https://localhost:9444/mcp",
  "authorization_servers": ["https://localhost:9443/realms/acme"],
  "scopes_supported": ["notes:read", "notes:write"],
  "dpop_signing_alg_values_supported": ["ES256"],
  "dpop_bound_access_tokens_required": true
}

Step 4: The agent

The agent is built on the official MCP TypeScript SDK. Its DPoP key is created at start-up and only lives in memory. It discovers Keycloak by itself from the MCP server's 401, gets a token with its certificate plus a DPoP proof, and adds a fresh proof to every MCP request through the SDK's custom fetch option:

const dpopFetch = (url, init = {}) => {
  const headers = new Headers(init.headers);
  headers.set("authorization", `DPoP ${token}`);
  headers.set("dpop", proof(init.method || "GET", url, token));   // fresh proof, bound to this token
  return mtlsFetch(url, { ...init, headers });                    // over mTLS, with the agent's certificate
};
await client.connect(new StreamableHTTPClientTransport(MCP_URL, { fetch: dpopFetch }));

Gotcha: the SDK's extractWWWAuthenticateParams only reads Bearer challenges. A server that requires DPoP answers with a DPoP challenge, so parse resource_metadata yourself (one regex), then use the SDK's discoverOAuthProtectedResourceMetadata and discoverAuthorizationServerMetadata as normal.

Running it:

→ notes-agent: calling https://localhost:9444/mcp without a token
  401, resource_metadata: https://localhost:9444/.well-known/oauth-protected-resource/mcp
→ authorization server: https://localhost:9443/realms/acme  (DPoP required: true)
→ token request: certificate CN=notes-agent, no client secret, DPoP key Kxt0XSOewtCv…
  token_type=DPoP  scope="notes:read"  aud=https://localhost:9444/mcp  cnf.jkt=Kxt0XSOewtCv…
→ MCP connected to notes: tools list_notes, delete_note
→ list_notes
  1. Rotate the agent certificates on Friday
  2. Review MCP tool permissions
→ delete_note {"id":1}
  ✖ insufficient_scope: notes-agent needs notes:write

A DPoP token for this MCP server only. The agent can list notes, and it can't delete them.

Step 5: Leak the token on purpose

Say the agent logged its token, or a prompt injection got it to print it. We took it from the agent's log and tried everything:

AttemptResult
Leaked token from outside, no client certificate403 no client certificate
From a compromised agent with a trusted certificate, as Bearer401 expected the DPoP scheme, got Bearer
Same, with a valid proof signed by its own key401 token is not bound to your key
Rogue agent (untrusted CA) at the MCP server403 certificate not signed by our CA
Rogue agent at KeycloakRefused in the TLS handshake (certificate unknown)
support-agent's own, valid token at the notes MCP server401 token is not for this MCP server (aud)

Every attempt is refused, and logged. A leaked agent token, on its own, gets an attacker nothing.

Before you go to production

  • Real workload identity for agent certificates (SPIFFE/SPIRE, cert-manager or a cloud CA): short-lived and rotated automatically.
  • Keep the agent's DPoP key in memory or in a TPM, HSM or KMS: never in config, logs or the model's context.
  • One audience per MCP server, one scope per sensitive tool. Review agent scopes like IAM roles.
  • Never log tokens, and still assume they leak: that's what DPoP is for.
  • Short token lifetimes for agents, so disabling an agent's client cuts it off within minutes.
  • A shared jti replay cache across MCP server instances, and client-certificate forwarding if a proxy sits in front.

Securing AI agents FAQ

Does Keycloak work as an authorization server for MCP?

Yes. The MCP server publishes protected resource metadata pointing at your Keycloak realm, and agents discover it from the 401. Keycloak issues the tokens; audiences come from an audience mapper on each client scope.

Why both mTLS and DPoP?

mTLS proves who the agent is, with no secret to leak, and keeps untrusted agents off the MCP server entirely. DPoP binds every token to the agent's key, so a token copied from a log or a prompt injection is useless on its own.

Can an agent act on behalf of a user?

Yes, with token exchange: the agent swaps a user's token for a narrower one for a specific MCP server. We'll cover that in a future guide.

Deploying AI agents or MCP servers? We design agent identity and MCP security with Keycloak for Australian organisations, from certificates to per-tool scopes. Talk to us.

Talk to a Keycloak specialist

The first conversation is free.

Make an enquiry