Skip to content
Go back

Cedar Policy Engine in Keycloak: Fine-Grained Authorization for Users and AI Agents via AuthZEN

Keycloak AuthZEN Cedar

Keycloak provides identity management and authorization services. With its experimental support for OpenID AuthZEN, it can also act as a standardized Policy Decision Point (PDP), allowing external Policy Enforcement Points (PEPs) to request authorization decisions.

But how are those decisions evaluated?

AuthZEN intentionally does not define that. The policy model, the policy language and the decision engine remain implementation choices.

We built an open source extension that integrates Cedar, an open source policy language and authorization engine, into Keycloak Authorization Services as a native policy type. Keycloak can then evaluate fine grained authorization policies for users and AI agents with Cedar, while PEPs such as Agent Gateway, an open source, AI first gateway for APIs and AI workloads, including LLM, MCP and A2A traffic, enforce its decisions through the standard AuthZEN interface.

AuthZEN standardizes how the question is asked. Cedar provides an open, analyzable language for the answer. Keycloak connects both, with the identities, roles and agents it already manages.

This article covers that combination, OpenID AuthZEN + Cedar + Keycloak, and what each part contributes. Broader topics such as agent authentication, workload identity federation, delegated authorization, and multi agent security will be explored in separate articles.

The extension is open source at embesozzi/keycloak-cedar-authorization. You can try it in two ways (see Try it yourself):

For the background and internal design, see the research article Keycloak Cedar Policy Engine.

Table of contents

Open Table of contents

Why AuthZEN and Cedar?

Authorization logic tends to end up in application code, gateway configuration, or proprietary policy formats. Each approach makes it harder to answer simple questions: who can do what, why was a request allowed, and what changes when a policy is updated?

Combining AuthZEN and Cedar changes that:

This also enables a Zero Trust approach: enforce authorization at multiple layers, not just at the API gateway. You can deploy PEPs at both the gateway and individual API levels, adding defense in depth, and with OpenID AuthZEN all of them use the same standard to ask for decisions (see Considerations for what each layer should decide).

Centralized policy decisions. Distributed enforcement. Interoperability.

OAuth 2.0 and OpenID Connect for identity, AuthZEN for the authorization decision API, and Cedar for policy definition and evaluation.

Open standards, open-source technologies, and no need to reinvent the wheel.

Cedar in five minutes

Cedar was created by AWS and is designed for fine grained access control. Its design goals are readability, safety and analyzability, and its semantics are formally specified and verified. The details are in the paper Cedar: A New Language for Expressive, Fast, Safe, and Analyzable Authorization.

The PARC model

Every Cedar request has four parts, often called PARC:

A policy grants or denies access for a combination of these:

@id("document-readers-read")
permit (
  principal in Keycloak::Role::"document-reader",
  action == Documents::Action::"read",
  resource is Documents::Document
);

permit, forbid and default deny

Cedar has three simple rules for combining policies:

  1. If no policy matches, the request is denied (default deny).
  2. If any permit matches and no forbid matches, the request is allowed.
  3. If any forbid matches, the request is denied, even if a permit also matches.

That last rule is what makes guardrails easy: a single forbid can block a dangerous action even if another team later writes a broad permit.

Schemas and validation

A Cedar schema declares the entity types, actions and context a policy may use. Policies are validated against it, so a typo in an attribute name or a comparison between the wrong types is caught before the policy is used, not at request time.

Here is the schema of the demo’s documents-api resource server (trimmed):

namespace Documents {
  entity Document = { name: String, type: String } tags Set<String>;

  type RequestContext = {
    acr?: String,        // authentication context
    amr?: Set<String>,   // authentication methods
    scope?: Set<String>, // token scopes
  };

  action read, write appliesTo {
    principal: [Keycloak::User, Keycloak::Client],
    resource: [Document],
    context: RequestContext,
  };
}

You can try Cedar policies and schemas in the browser with the playground on cedarpolicy.com, and read the full language reference in the Cedar documentation.

AuthZEN and Cedar in Keycloak

The extension registers cedar as a native policy type in Keycloak Authorization Services. Cedar policies participate in Keycloak’s existing resource, scope and permission model. Cedar runs inside Keycloak through cedar-java, so no external PDP is required.

sequenceDiagram participant PEP as PEP <br/> (API Gateway, Agent Gateway <br/> or MCP Server) participant KC as Keycloak <br/> (AuthZEN endpoint) participant AS as Authorization Services participant CP as Cedar policy provider PEP->>KC: POST /realms/{realm}/authzen/access/v1/evaluation KC->>AS: Evaluate resource + scope for the subject AS->>CP: Evaluate the permission's Cedar policy CP->>CP: Build the Cedar request from Keycloak's data and the schema CP-->>AS: grant / deny AS-->>KC: decision KC-->>PEP: { "decision": true | false }
  1. The PEP sends an AuthZEN evaluation request to Keycloak.
  2. Keycloak maps it to its Authorization Services: the resource, the scope and the subject.
  3. The Cedar policy provider builds the Cedar request and evaluates the resource server’s policies.
  4. The PEP enforces the decision: forward the request, or reject it.

From an AuthZEN request to a Cedar request

Each part of the AuthZEN request becomes part of the Cedar request:

AuthZENKeycloakCedar
subjectUser, or the service account of a clientKeycloak::User / Keycloak::Client
resourceResource (type and name)Documents::Document::"document-1"
actionAuthorization scopeDocuments::Action::"read"
contextEvaluation contextcontext, declared keys only

Two design choices matter here:

Other properties of the extension:

Use cases

The demo realm has three users, one AI agent and two resource servers: documents-api for documents and mcp-server for MCP tools. The main scenarios are covered by automated tests, including end to end AuthZEN evaluations against the demo realm.

1. Users by role

Scenario: readers may read documents, writers may write them.

@id("document-readers-read")
permit (
  principal in Keycloak::Role::"document-reader",
  action == Documents::Action::"read",
  resource is Documents::Document
);

@id("document-writers-write")
permit (
  principal in Keycloak::Role::"document-writer",
  action == Documents::Action::"write",
  resource is Documents::Document
);

The PEP asks:

{
  "subject":  { "type": "user", "id": "alice" },
  "resource": { "type": "Document", "id": "document-1" },
  "action":   { "name": "read" }
}
SubjectActionDecision
alice (document-reader)readtrue
alicewritefalse
bob (document-writer)writetrue
alice, sending "properties": { "roles": "document-writer" }writefalse

The last row is the important one: Keycloak resolves the user’s effective roles (direct, composite and inherited from groups), so a role claimed in the request is ignored.

AuthZEN carries the question, Keycloak supplies the roles, Cedar states the rule.

2. Passkey login required to write

Scenario: editors may change a document only when they logged in with a passkey. A password login is not enough.

How the user logged in is known by the application and its token (acr, amr), so the PEP passes it in the AuthZEN context, and the policy checks it:

@id("editors-write-with-passkey")
permit (
  principal in Keycloak::Role::"document-editor",
  action == Documents::Action::"write",
  resource is Documents::Document
)
when
{
  context has acr &&
  context.acr == "inherence" &&
  context has amr &&
  context.amr.contains("passkeys")
};
{
  "subject":  { "type": "user", "id": "carol" },
  "resource": { "type": "Document", "id": "document-1" },
  "action":   { "name": "write" },
  "context":  { "acr": "inherence", "amr": ["passkeys", "mfa"] }
}
SubjectContextDecision
carol (document-editor)acr inherence, amr ["passkeys", "mfa"]true
carolacr inherence, amr ["pwd"]false

These acr and amr values are configured in this demo; they are not standard registered values.

This combines authorization and authentication context in a single, readable rule: AuthZEN carries the login facts in context, Keycloak supplies the role, Cedar checks both with typed values. For more on stronger authentication at the moment of a sensitive action, see Keycloak Step Up and MFA for Web Apps and APIs.

3. An AI agent identified by its workload identity

Scenario: only one specific agent, the planner agent, may read documents.

The agent is registered in Keycloak as a client whose clientId is its SPIFFE ID. Cedar represents it as a Keycloak::Client principal, allowing policies to reference that identity:

@id("planner-agent-read")
permit (
  principal is Keycloak::Client,
  action == Documents::Action::"read",
  resource is Documents::Document
)
when { principal.clientId == "spiffe://example.org/ns/agents/sa/planner-agent" };
SubjectActionDecision
planner agentreadtrue
planner agentwritefalse

Keycloak holds the agent registration, Cedar references the agent’s client identity, and AuthZEN gives authorized PEPs a standard way to ask about it. How the agent is sent as the AuthZEN subject is explained in How an AI agent is identified.

4. An AI agent calling MCP tools

Scenario: a gateway in front of an MCP server checks every tools/call with Keycloak. Support agents may call the customer read tools when their token grants mcp:tools, and no agent may ever delete a customer.

Each MCP tool is a Keycloak resource of type Tool, named after the tool, with the scope call:

// Support agents may call the customer read tools, when their token grants mcp:tools.
@id("support-agents-call-customer-read-tools")
permit (
  principal is Keycloak::Client,
  action == Mcp::Action::"call",
  resource is Mcp::Tool
)
when
{
  resource in [Mcp::Tool::"get_customer", Mcp::Tool::"list_customers"] &&
  principal.roles.contains("support-agent") &&
  context has scope &&
  context.scope.contains("mcp:tools")
};

When the agent sends this MCP request:

{
  "jsonrpc": "2.0",
  "id": 3,
  "method": "tools/call",
  "params": { "name": "get_customer", "arguments": { "id": "cust-12345" } }
}

the gateway asks Keycloak, through AuthZEN, whether this agent may call the tool get_customer, and passes the token’s scopes in the context: { "scope": ["mcp:tools"] }. Cedar evaluates the request with the agent as the principal (Keycloak::Client).

Agent roleToolscope in contextDecisionDecided by
support-agentget_customer, list_customers["mcp:tools"]truesupport-agents-call-customer-read-tools
support-agentget_customermissingfalseno permit matches
support-agentdelete_customer["mcp:tools"]falseno permit matches (default deny)

AuthZEN gives the MCP gateway one standard call per tools/call, Keycloak models each tool as a resource, and Cedar expresses the allow list; anything not listed is denied by default.

In the extension’s demo, a test script plays the gateway’s role and sends these requests. To see Cedar decisions enforced by a real gateway, see Try it yourself.

How an AI agent is identified

In this demo, AI agents authenticate using OAuth 2.0 client credentials. The extension resolves the authenticated agent to its associated Keycloak client and represents it as a Keycloak::Client principal in Cedar. This allows Cedar policies to authorize agents using their client identity, including workload identifiers such as SPIFFE IDs.

In Keycloak, a client using client credentials can have an associated service account, represented as a user. The PEP therefore sends the service account user ID with subject type user. The extension resolves the associated client and represents the agent as a Keycloak::Client principal in Cedar.

In delegated authorization scenarios, where an agent acts on behalf of a user (On Behalf Of, or OBO), the agent’s identity can be represented by a token claim such as act (actor), when using OAuth 2.0 Token Exchange (RFC 8693). These scenarios, including token exchange and delegated identity, will be explored in a separate article.

Verifiable policies as code

Cedar policies are more than code in a repository: they are verifiable. Each resource server’s schema and policies live in Git, and every policy can be validated in CI against the same schema Keycloak uses, as the extension repository does, and is validated again by Keycloak when it is saved. An invalid policy never reaches a decision.

In the demo, each .cedar file becomes one Keycloak policy, so a decision in the logs, such as documents#document-readers-read, points directly to its file and statement.

Try it yourself

Both options run Keycloak with the Cedar extension. They differ in what sends the AuthZEN requests to Keycloak:

In front of Keycloak (the PEP)What you see
Option 1: Keycloak onlyA test script, sending AuthZEN requests with curlThe four use cases of this article
Option 2: Keycloak with Agent GatewayAgent Gateway, before every MCP tools/call to a Payments MCP serverA different MCP example: users calling Payments tools through a real gateway

Option 1: Keycloak only

This is the quickest way to see the Cedar policies decide. It runs Keycloak with the Cedar extension and a demo realm (the users, the agent and both resource servers of this article). A test script plays the PEP: it sends the AuthZEN requests of every use case above and checks each decision. It requires Java 17, Maven, Docker, curl and jq.

git clone https://github.com/embesozzi/keycloak-cedar-authorization
cd keycloak-cedar-authorization

make up              # build, start Keycloak on http://localhost:8082, configure the demo realm
make test-e2e-run    # run the AuthZEN checks of the use cases
make down            # stop Keycloak and delete its data

The demo credentials are fixed values for local use only.

Option 2: Keycloak with Agent Gateway

The agentic-security-labs repository runs Keycloak with the Cedar extension with a real PEP: Agent Gateway sits in front of a Payments MCP server and asks Keycloak before every tools/call. Keycloak evaluates the decision with Cedar policies.

This lab runs a different MCP example from Use case 4: instead of an AI agent calling customer tools, users (alice, bob and carol) call Payments tools, and Cedar policies authorize them by their roles.

git clone --branch v1.1.0 https://github.com/embesozzi/agentic-security-labs.git
cd agentic-security-labs

make up-cedar   # Keycloak with the Cedar provider, Agent Gateway and the MCP server
make test       # run the use cases
make down       # stop the lab

Only managers and admins may approve or cancel a payment. In Cedar, that rule reads:

@id("managers-approve-and-cancel")
permit (
  principal,
  action == Payments::Action::"tools/call",
  resource is Payments::tool
)
when {
  resource in [
    Payments::tool::"approve_payment",
    Payments::tool::"cancel_payment"
  ] &&
  (principal in Keycloak::Role::"payments_manager" ||
   principal in Keycloak::Role::"payments_admin")
};

For comparison, the lab can also run the same use cases without Cedar, with Keycloak’s default policies (make up in agentic-security-labs). The decisions are the same: Agent Gateway and the AuthZEN request do not change, only the policy engine does. The lab README compares both options, and Implementing OpenID AuthZEN in Agent Gateway explains the PEP side.

Considerations

The extension is experimental and not recommended for production use. A few points to keep in mind when designing with it:

Conclusion

AuthZEN and Cedar solve different problems, and that is exactly why they fit together. With the Cedar policy provider, Keycloak evaluates fine grained, testable policies for users and AI agents, using the identities, roles and agent registrations it already manages, behind a standard AuthZEN endpoint.

The PEP enforces the decision. Keycloak makes the decision. AuthZEN asks the question, and Cedar expresses the answer.

Keep it simple, modular, and interoperable. Less buzzwords, more design.

References


Share this post:

Next Post
Implementing OpenID AuthZEN in Agent Gateway: MCP Tool Authorization