OpenFGA
Since Camel 4.23
Both producer and consumer are supported
The OpenFGA component turns a Camel route into a Policy Enforcement Point (PEP) in front of OpenFGA, the CNCF authorization engine that implements Google’s Zanzibar model. Where a policy engine asks what do the rules say, OpenFGA answers a different question: what is this subject’s relationship to this resource.
That distinction is the reason the component exists. Expressing "anne may read document:budget because she owns the folder it lives in" as policy-as-code means shipping the relationship graph into the policy input on every message, which does not scale past a handful of relationships. OpenFGA keeps the graph — a set of (user, relation, object) tuples — in the decision point, and the route asks it a question instead of handing it data.
The component is a companion to camel-opa and camel-spiffe, and deliberately shares camel-opa’s shape and its security posture, so that an operator who knows one knows the other:
| establishes who the caller is (workload identity, X.509-SVID / JWT-SVID) |
| evaluates what the rules say (policy-as-code, Rego) |
camel-openfga | answers what the caller’s relationship to the resource is (ReBAC, relationship tuples) |
Maven users will need to add the following dependency to their pom.xml.
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-openfga</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency> URI Format
openfga:operation[?options]
Where operation is one of check, batchCheck, listObjects, streamedListObjects, listRelations, listUsers, readTuples, readChanges, expand, writeTuples, deleteTuples or write.
Configuring Options
Camel components are configured on two separate levels:
-
component level
-
endpoint level
Configuring Component Options
At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.
For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.
Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.
You can configure components using:
-
the Component DSL.
-
in a configuration file (
application.properties,*.yamlfiles, etc). -
directly in the Java code.
Configuring Endpoint Options
You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.
Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.
A good practice when configuring options is to use Property Placeholders.
Property placeholders provide a few benefits:
-
They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.
-
They allow externalizing the configuration from the code.
-
They help the code to become more flexible and reusable.
The following two sections list all the options, firstly for the component followed by the endpoint.
Component Options
The OpenFGA component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
The base URL of the OpenFGA HTTP API, without a trailing slash, for example http://openfga:8080. The default is OpenFGA on its standard HTTP port on the local host. | String | ||
The identifier of the authorization model revision to evaluate against. Leave it empty to use whichever model the store considers latest. Pin it in production. A store keeps every model it was ever given and latest moves the moment somebody writes a new one, so an unpinned endpoint can start answering a different question than the one it was reviewed with - without any change to the route. Pinning also makes a model rollout a deliberate, reviewable configuration change. | String | ||
Whether batchCheck fans out individual checks (client, the compatible default) or uses the native server BatchCheck API (server, requires OpenFGA 1.8.0 or later). Server mode chunks checks by maxBatchSize and correlates responses back to the original objects. Failures never fall back to an unfiltered result or another mode. Enum values:
| client | OpenFgaBatchCheckMode | |
The context for the conditions (CEL expressions) of conditional relationship tuples, as a Map looked up from the registry, for example #myContext. Used by check, batchCheck, listObjects, streamedListObjects, listRelations and listUsers. Give each value the Java type of its condition parameter: OpenFGA rejects a value of the wrong type with HTTP 400, which fails the exchange also when failOpen is enabled. | Map | ||
The component configuration. | OpenFgaConfiguration | ||
The consistency the query is answered with. OpenFGA’s default, MINIMIZE_LATENCY, may answer from a replica that has not caught up yet, which right after a revoke means a tuple that was deleted can still grant access for a moment. Set HIGHER_CONSISTENCY on the paths where that window matters, at the cost of latency. Left unset, OpenFGA’s own default applies. Enum values:
| String | ||
Relationship tuples that apply to one query only and are never stored, as semicolon-separated user,relation,object triples, each part a Simple expression, for example user:$\{exchangeProperty.authenticatedSubject},member,team:eng. Used by check, batchCheck, listObjects, streamedListObjects, listRelations and listUsers. A contextual tuple grants access exactly like a stored tuple, so derive it from what the route established, never from a header the caller sent. When a part resolves to blank or to an invalid value, the exchange is denied with the reason invalid-contextual-tuple. | String | ||
The page to read from, for readTuples and readChanges. Evaluated as a Simple expression against the exchange, so a route can feed back the token the previous page returned - $\{header.CamelOpenFgaContinuationToken} - and page through without the token being configured statically. | String | ||
The object as an OpenFGA identifier such as document:budget, evaluated as a Simple expression against each exchange, so document:$\{header.documentId} names the resource the message is about. It is the object to check for check, listRelations, listUsers and expand, the object of the tuple for writeTuples, deleteTuples and write, and a filter for readTuples, where a type alone such as document: is also accepted. Taking it from a header is safe: the check decides whether the caller may access it. | String | ||
How writeTuples and write handle an existing relationship: error (the default) fails the operation, while ignore leaves that relationship unchanged and continues. The ignore mode requires OpenFGA 1.10.0 or later. Enum values:
| error | OpenFgaWriteConflictMode | |
How deleteTuples and write handle an absent relationship: error (the default) fails the operation, while ignore skips that deletion and continues. The ignore mode requires OpenFGA 1.10.0 or later. Enum values:
| error | OpenFgaWriteConflictMode | |
How many entries a readTuples or readChanges page returns. Left unset, OpenFGA’s own default applies. A page is one request: this bounds the answer, not the number of requests a route makes. | Integer | ||
The relation, such as reader or owner, evaluated as a Simple expression against each exchange. It is the permission demanded by check, batchCheck, listObjects, streamedListObjects, listUsers and expand, the relation of the tuple for writeTuples, deleteTuples and write, and a filter for readTuples. Keep it literal: resolving it from an inbound header lets the caller pick the weakest relation the authorization model defines. | String | ||
Comma-separated list of relations the listRelations operation asks about, for example reader,writer,owner. Only the ones the subject actually holds come back. | String | ||
The earliest change readChanges returns, as an ISO-8601 timestamp such as 2026-10-01T00:00:00Z. Without it, reading starts at the beginning of the change log of the store. The consumer uses it only while the checkpointRepository holds no position yet. A malformed value fails the endpoint when it starts. | String | ||
Required The identifier of the OpenFGA store holding the relationship tuples and the authorization model, as returned by fga store create. The store is the relationship graph that judges the exchange, so it comes from the endpoint only and is never taken from a message header. | String | ||
The object type from the authorization model, for example document, taken literally. Required for listObjects and streamedListObjects, which list the objects of this type. Optional for readChanges, where it limits the changes to objects of this type. | String | ||
The user (subject) as an OpenFGA identifier such as user:anne, evaluated as a Simple expression against each exchange. It is the subject to authorize for check, batchCheck, listObjects, streamedListObjects and listRelations, the user of the tuple for writeTuples, deleteTuples and write, and a filter for readTuples. Take it from an exchange property set by the step that verified the caller, for example user:$\{exchangeProperty.CamelKeycloakTokenSubject}, and not from a header the caller sent, which would let the caller choose who to be. When it resolves to blank or to a bare type prefix such as user:, the check and list operations deny the exchange (an empty list for the list operations), also when failOpen is enabled. | String | ||
Comma-separated list of user filters for the listUsers operation, naming which kinds of subject to return. An entry is either a type, user, or a type and a relation, team#member, to return the usersets holding the relation rather than the individual subjects. Defaults to user. | String | ||
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
The key under which the readChanges consumer stores its continuation token in the checkpointRepository. Required for the consumer. Use a key of its own for each consumer: consumers that share a key overwrite each other’s position. | String | ||
The StateRepository that stores the continuation token of the change log, so the readChanges consumer resumes where it stopped after a restart. Required for the consumer. The token is saved only after the whole page was routed successfully, so a page that failed is read again. A repository that is not started yet is started and stopped with the consumer. | StateRepository | ||
How long the readChanges consumer waits for the change log request of one poll before the poll fails. Must be positive. | 30000 | long | |
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
Autowired The OpenFgaStreamingClient that opens the HTTP request of streamedListObjects. Required when openFgaClient is set; otherwise the component builds one from apiUrl, the credentials and sslContextParameters. The application owns the lifecycle of a client set here. | OpenFgaStreamingClient | ||
The maximum length, in characters, of one line (one JSON record) of the streamedListObjects response. A longer line fails the iteration. Must be positive. | 65536 | int | |
The maximum number of objects streamedListObjects returns. When the server streams more, the iteration fails instead of returning a truncated result. Must be positive. | 10000 | int | |
Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | |
How long to wait for the connection to OpenFGA to be established. The component sets it on the Java HttpClient it builds for the SDK. Must be positive. | 10000 | long | |
Maximum number of checks per native server BatchCheck request, from 1 to 50. Applies only when batchCheckMode=server; the SDK splits larger input lists into requests of at most this size. 50 is the default per-request limit of an OpenFGA server (max-checks-per-batch-check). | 50 | int | |
How many HTTP requests a batchCheck may have in flight at once, at least 1. In client mode each request checks one object; in server mode each request checks up to maxBatchSize objects. | 10 | int | |
How many times the SDK retries a request that failed with a network error, HTTP 429 or a 5xx response other than 501. From 0 (no retries) to 15. More retries also make one exchange wait longer. | 3 | int | |
Autowired An existing OpenFgaClient to use instead of one built by the component. The client then sets the server, store, credentials, TLS and HTTP timeouts, so apiUrl, storeId, the credentials, sslContextParameters, connectTimeout, readTimeout and maxRetries do not configure it; the timeouts and maxRetries still bound how long the component waits for an answer. No producer health check is registered. streamedListObjects also needs streamingClient, storeId and a positive readTimeout. | OpenFgaClient | ||
How long to wait for one HTTP request to OpenFGA to complete, set as the timeout of each request the SDK sends. Must be positive. A check that times out has no verdict, so the exchange fails, unless failOpen is enabled. | 10000 | long | |
Used for enabling or disabling all consumer based health checks from this component. | true | boolean | |
Used for enabling or disabling all producer based health checks from this component. Notice: Camel has by default disabled all producer based health-checks. You can turn on producer checks globally by setting camel.health.producersEnabled=true. | true | boolean | |
The audience to request the access token for in the client-credentials flow. | String | ||
Pre-shared key sent to OpenFGA as a Bearer token in the Authorization header, for a server started with --authn-method preshared. Takes precedence over clientId. | String | ||
The token endpoint of the OAuth 2.0 client-credentials flow, for example https://issuer.example.com/oauth/token. The SDK adds https:// when no scheme is given, and the path /oauth/token when the URL has no path. | String | ||
Client identifier for the OAuth 2.0 client-credentials flow, for a server that authenticates through an OIDC provider. Setting it (without apiToken) selects that flow, which then requires clientSecret and apiTokenIssuer; apiAudience and scopes are optional. | String | ||
Client secret for the OAuth 2.0 client-credentials flow. | String | ||
Whether to let the exchange proceed when OpenFGA could not answer: the server is unreachable, the request timed out, or it answered HTTP 429 or 5xx. Such an exchange gets CamelOpenFgaAllowed=true and CamelOpenFgaFailedOpen=true. Applies only to the check operation and to OpenFgaSecurityPolicy; a deny, a subject or object that could not be used, and any other error are never turned into an allow, and the other operations always fail. Do not enable this in production. | false | boolean | |
Space-separated scopes to request in the client-credentials flow. | String | ||
TLS configuration for the connection to OpenFGA. Needed to trust a server whose certificate comes from a private CA, and to present a client certificate to a server that requires mutual TLS - a SPIFFE X.509-SVID obtained with camel-spiffe, for instance, so the workload authenticates to the decision point as itself. | SSLContextParameters | ||
Enable usage of global SSL context parameters. | false | boolean |
Endpoint Options
The OpenFGA endpoint is configured using URI syntax:
openfga:operation
With the following path and query parameters:
Path Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Required The operation to perform. The operation is taken from the endpoint only: it is deliberately not overridable by a message header, so that an inbound message cannot turn a check into a tuple write, nor a check for one relation into a check for a weaker one. Enum values:
| OpenFgaOperation |
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
The base URL of the OpenFGA HTTP API, without a trailing slash, for example http://openfga:8080. The default is OpenFGA on its standard HTTP port on the local host. | String | ||
The identifier of the authorization model revision to evaluate against. Leave it empty to use whichever model the store considers latest. Pin it in production. A store keeps every model it was ever given and latest moves the moment somebody writes a new one, so an unpinned endpoint can start answering a different question than the one it was reviewed with - without any change to the route. Pinning also makes a model rollout a deliberate, reviewable configuration change. | String | ||
Whether batchCheck fans out individual checks (client, the compatible default) or uses the native server BatchCheck API (server, requires OpenFGA 1.8.0 or later). Server mode chunks checks by maxBatchSize and correlates responses back to the original objects. Failures never fall back to an unfiltered result or another mode. Enum values:
| client | OpenFgaBatchCheckMode | |
The context for the conditions (CEL expressions) of conditional relationship tuples, as a Map looked up from the registry, for example #myContext. Used by check, batchCheck, listObjects, streamedListObjects, listRelations and listUsers. Give each value the Java type of its condition parameter: OpenFGA rejects a value of the wrong type with HTTP 400, which fails the exchange also when failOpen is enabled. | Map | ||
The consistency the query is answered with. OpenFGA’s default, MINIMIZE_LATENCY, may answer from a replica that has not caught up yet, which right after a revoke means a tuple that was deleted can still grant access for a moment. Set HIGHER_CONSISTENCY on the paths where that window matters, at the cost of latency. Left unset, OpenFGA’s own default applies. Enum values:
| String | ||
Relationship tuples that apply to one query only and are never stored, as semicolon-separated user,relation,object triples, each part a Simple expression, for example user:$\{exchangeProperty.authenticatedSubject},member,team:eng. Used by check, batchCheck, listObjects, streamedListObjects, listRelations and listUsers. A contextual tuple grants access exactly like a stored tuple, so derive it from what the route established, never from a header the caller sent. When a part resolves to blank or to an invalid value, the exchange is denied with the reason invalid-contextual-tuple. | String | ||
The page to read from, for readTuples and readChanges. Evaluated as a Simple expression against the exchange, so a route can feed back the token the previous page returned - $\{header.CamelOpenFgaContinuationToken} - and page through without the token being configured statically. | String | ||
The object as an OpenFGA identifier such as document:budget, evaluated as a Simple expression against each exchange, so document:$\{header.documentId} names the resource the message is about. It is the object to check for check, listRelations, listUsers and expand, the object of the tuple for writeTuples, deleteTuples and write, and a filter for readTuples, where a type alone such as document: is also accepted. Taking it from a header is safe: the check decides whether the caller may access it. | String | ||
How writeTuples and write handle an existing relationship: error (the default) fails the operation, while ignore leaves that relationship unchanged and continues. The ignore mode requires OpenFGA 1.10.0 or later. Enum values:
| error | OpenFgaWriteConflictMode | |
How deleteTuples and write handle an absent relationship: error (the default) fails the operation, while ignore skips that deletion and continues. The ignore mode requires OpenFGA 1.10.0 or later. Enum values:
| error | OpenFgaWriteConflictMode | |
How many entries a readTuples or readChanges page returns. Left unset, OpenFGA’s own default applies. A page is one request: this bounds the answer, not the number of requests a route makes. | Integer | ||
The relation, such as reader or owner, evaluated as a Simple expression against each exchange. It is the permission demanded by check, batchCheck, listObjects, streamedListObjects, listUsers and expand, the relation of the tuple for writeTuples, deleteTuples and write, and a filter for readTuples. Keep it literal: resolving it from an inbound header lets the caller pick the weakest relation the authorization model defines. | String | ||
Comma-separated list of relations the listRelations operation asks about, for example reader,writer,owner. Only the ones the subject actually holds come back. | String | ||
The earliest change readChanges returns, as an ISO-8601 timestamp such as 2026-10-01T00:00:00Z. Without it, reading starts at the beginning of the change log of the store. The consumer uses it only while the checkpointRepository holds no position yet. A malformed value fails the endpoint when it starts. | String | ||
Required The identifier of the OpenFGA store holding the relationship tuples and the authorization model, as returned by fga store create. The store is the relationship graph that judges the exchange, so it comes from the endpoint only and is never taken from a message header. | String | ||
The object type from the authorization model, for example document, taken literally. Required for listObjects and streamedListObjects, which list the objects of this type. Optional for readChanges, where it limits the changes to objects of this type. | String | ||
The user (subject) as an OpenFGA identifier such as user:anne, evaluated as a Simple expression against each exchange. It is the subject to authorize for check, batchCheck, listObjects, streamedListObjects and listRelations, the user of the tuple for writeTuples, deleteTuples and write, and a filter for readTuples. Take it from an exchange property set by the step that verified the caller, for example user:$\{exchangeProperty.CamelKeycloakTokenSubject}, and not from a header the caller sent, which would let the caller choose who to be. When it resolves to blank or to a bare type prefix such as user:, the check and list operations deny the exchange (an empty list for the list operations), also when failOpen is enabled. | String | ||
Comma-separated list of user filters for the listUsers operation, naming which kinds of subject to return. An entry is either a type, user, or a type and a relation, team#member, to return the usersets holding the relation rather than the individual subjects. Defaults to user. | String | ||
The key under which the readChanges consumer stores its continuation token in the checkpointRepository. Required for the consumer. Use a key of its own for each consumer: consumers that share a key overwrite each other’s position. | String | ||
The StateRepository that stores the continuation token of the change log, so the readChanges consumer resumes where it stopped after a restart. Required for the consumer. The token is saved only after the whole page was routed successfully, so a page that failed is read again. A repository that is not started yet is started and stopped with the consumer. | StateRepository | ||
If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead. | false | boolean | |
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
How long the readChanges consumer waits for the change log request of one poll before the poll fails. Must be positive. | 30000 | long | |
To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | ExceptionHandler | ||
Sets the exchange pattern when the consumer creates an exchange. Enum values:
| ExchangePattern | ||
A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel. | PollingConsumerPollStrategy | ||
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
Autowired The OpenFgaStreamingClient that opens the HTTP request of streamedListObjects. Required when openFgaClient is set; otherwise the component builds one from apiUrl, the credentials and sslContextParameters. The application owns the lifecycle of a client set here. | OpenFgaStreamingClient | ||
The maximum length, in characters, of one line (one JSON record) of the streamedListObjects response. A longer line fails the iteration. Must be positive. | 65536 | int | |
The maximum number of objects streamedListObjects returns. When the server streams more, the iteration fails instead of returning a truncated result. Must be positive. | 10000 | int | |
How long to wait for the connection to OpenFGA to be established. The component sets it on the Java HttpClient it builds for the SDK. Must be positive. | 10000 | long | |
Maximum number of checks per native server BatchCheck request, from 1 to 50. Applies only when batchCheckMode=server; the SDK splits larger input lists into requests of at most this size. 50 is the default per-request limit of an OpenFGA server (max-checks-per-batch-check). | 50 | int | |
How many HTTP requests a batchCheck may have in flight at once, at least 1. In client mode each request checks one object; in server mode each request checks up to maxBatchSize objects. | 10 | int | |
How many times the SDK retries a request that failed with a network error, HTTP 429 or a 5xx response other than 501. From 0 (no retries) to 15. More retries also make one exchange wait longer. | 3 | int | |
Autowired An existing OpenFgaClient to use instead of one built by the component. The client then sets the server, store, credentials, TLS and HTTP timeouts, so apiUrl, storeId, the credentials, sslContextParameters, connectTimeout, readTimeout and maxRetries do not configure it; the timeouts and maxRetries still bound how long the component waits for an answer. No producer health check is registered. streamedListObjects also needs streamingClient, storeId and a positive readTimeout. | OpenFgaClient | ||
How long to wait for one HTTP request to OpenFGA to complete, set as the timeout of each request the SDK sends. Must be positive. A check that times out has no verdict, so the exchange fails, unless failOpen is enabled. | 10000 | long | |
The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in. | int | ||
The number of subsequent idle polls that should happen before the backoffMultipler should kick-in. | int | ||
To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured. | int | ||
Milliseconds before the next poll. | 500 | long | |
If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages. | false | boolean | |
How long a poll may run before the health check of the consumer reports DOWN. The health check is otherwise based on the polls that are done, so it stays UP while a poll hangs, for example on a read without timeout from a connection that went silent. A poll includes routing the messages it polled, so set this above the longest poll you expect. The poll is not interrupted. The value is in millis (not affected by timeUnit). The default 0 turns this off. | 0 | long | |
Milliseconds before the first poll starts. | 1000 | long | |
Specifies a maximum limit of number of fires. So if you set it to 1, the scheduler will only fire once. If you set it to 5, it will only fire five times. A value of zero or negative means fire forever. | 0 | long | |
The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that. Enum values:
| TRACE | LoggingLevel | |
Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool. | ScheduledExecutorService | ||
To use a cron scheduler from either camel-spring or camel-quartz component. Use value spring or quartz for built in scheduler. | none | Object | |
To configure additional properties when using a custom scheduler or any of the Quartz, Spring based scheduler. This is a multi-value option with prefix: scheduler. | Map | ||
Whether the scheduler should be auto started. | true | boolean | |
Time unit for initialDelay and delay options. Enum values:
| MILLISECONDS | TimeUnit | |
Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details. | true | boolean | |
The audience to request the access token for in the client-credentials flow. | String | ||
Pre-shared key sent to OpenFGA as a Bearer token in the Authorization header, for a server started with --authn-method preshared. Takes precedence over clientId. | String | ||
The token endpoint of the OAuth 2.0 client-credentials flow, for example https://issuer.example.com/oauth/token. The SDK adds https:// when no scheme is given, and the path /oauth/token when the URL has no path. | String | ||
Client identifier for the OAuth 2.0 client-credentials flow, for a server that authenticates through an OIDC provider. Setting it (without apiToken) selects that flow, which then requires clientSecret and apiTokenIssuer; apiAudience and scopes are optional. | String | ||
Client secret for the OAuth 2.0 client-credentials flow. | String | ||
Whether to let the exchange proceed when OpenFGA could not answer: the server is unreachable, the request timed out, or it answered HTTP 429 or 5xx. Such an exchange gets CamelOpenFgaAllowed=true and CamelOpenFgaFailedOpen=true. Applies only to the check operation and to OpenFgaSecurityPolicy; a deny, a subject or object that could not be used, and any other error are never turned into an allow, and the other operations always fail. Do not enable this in production. | false | boolean | |
Space-separated scopes to request in the client-credentials flow. | String | ||
TLS configuration for the connection to OpenFGA. Needed to trust a server whose certificate comes from a private CA, and to present a client certificate to a server that requires mutual TLS - a SPIFFE X.509-SVID obtained with camel-spiffe, for instance, so the workload authenticates to the decision point as itself. | SSLContextParameters |
Message Headers
The OpenFGA component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
CamelOpenFgaAllowed (producer) Constant: | Whether access is allowed: the verdict of check, and for batchCheck true when at least one object is allowed. Also set to false when the exchange is denied because the user, object, relation or a contextual tuple could not be used. Any inbound value is removed before the check. | Boolean | |
CamelOpenFgaDenyReason (producer) Constant: | Why the exchange was denied, set only on a deny. denied when OpenFGA evaluated the relationship and answered no; missing-user, missing-object, missing-relation, wildcard-subject or invalid-identifier when the exchange never reached OpenFGA because what it carried could not be used as a subject or an object; invalid-contextual-tuple when a configured contextual tuple did not resolve, so the check would have asked a different question than the endpoint was configured to ask. | String | |
CamelOpenFgaFailedOpen (producer) Constant: | Set to true only when the exchange proceeded because failOpen is enabled and OpenFGA could not be asked - nothing authorized it. Absent on every verdict OpenFGA actually gave, so a route or an audit trail can tell the two apart rather than seeing the same CamelOpenFgaAllowed=true for both. | Boolean | |
| Constant: | The user the operation resolved from the user option, set by check, batchCheck, listObjects, streamedListObjects and listRelations for auditing. Never read as an input. | String | |
| Constant: | The object the operation resolved from the object option, set by check, listRelations, listUsers and expand for auditing. Never read as an input. | String | |
CamelOpenFgaRelation (producer) Constant: | The relation the operation resolved from the relation option, set by check, batchCheck, listObjects, streamedListObjects, listUsers and expand for auditing. Never read as an input, so it cannot demand a weaker permission than the endpoint configured. | String | |
CamelOpenFgaStoreId (producer) Constant: | The storeId of the endpoint, set with the verdict of the check operation and whenever an operation denies the exchange, so an audit trail records which store decided. | String | |
CamelOpenFgaContinuationToken (producer) Constant: | The continuation token the page came back with. Feed it back through the continuationToken option to read on. The two operations end differently: readTuples returns no token on its last page, so the header is absent once the read is done, whereas readChanges always returns a token - an empty body is what says the log has been read up to date, and that last token is what lets the next poll resume instead of replaying the whole log. | String | |
CamelOpenFgaWrittenTuples (producer) Constant: | How many relationship tuples a successful writeTuples or write operation submitted. Ignored duplicate writes are included in this count. | Integer | |
CamelOpenFgaDeletedTuples (producer) Constant: | How many relationship tuples a successful deleteTuples or write operation submitted for deletion. Ignored missing deletes are included in this count. | Integer |
Message Body
The message body at each side of the OpenFGA component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.
| Side | Body | Description |
|---|---|---|
Consumer |
| readChanges: one ordered page of change Maps, acknowledged after successful page processing. |
Producer input |
| batchCheck: the objects to check, as a List or comma-separated text. writeTuples and deleteTuples: a Map with user, relation and object, a ClientTupleKey, or a List of them, used only when none of user, relation and object is configured; text fails, unmarshal JSON first. write: a Map containing writes/deletes collections of Maps with exactly user, relation and object entries. Other operations do not read the body.
Not known when |
Producer output |
| check, writeTuples, deleteTuples and write keep the body: the verdict is in the CamelOpenFgaAllowed header, the count in CamelOpenFgaWrittenTuples or CamelOpenFgaDeletedTuples. batchCheck: the allowed objects of the body; listObjects, listRelations and listUsers: a List of String identifiers; streamedListObjects: a closeable OpenFgaObjectIterator; readTuples and readChanges: a List of Maps with user, relation, object and timestamp (and operation for a change); expand: the UsersetTree, or null when the object or relation does not resolve.
|
The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.
Resolving the subject and the object
user, object and relation are evaluated as Simple expressions against each Exchange, so a literal is used as written and an expression resolves per message:
-
Java
-
YAML
to("openfga:check"
+ "?storeId=01HQMVAJ..."
+ "&relation=reader"
+ "&user=user:${exchangeProperty.CamelKeycloakTokenSubject}"
+ "&object=document:${header.documentId}"); - route:
from:
uri: direct:checkDocument
steps:
- to:
uri: openfga:check
parameters:
storeId: "01HQMVAJ..."
relation: reader
user: "user:${exchangeProperty.CamelKeycloakTokenSubject}"
object: "document:${header.documentId}" The component evaluates these itself, per Exchange, so a plain to() is enough — there is no need for toD() and the endpoint cache it churns.
| Read the subject from an exchange property, not a header An endpoint configured as Put the subject where the caller cannot reach it. An exchange property set by the step in your route that verified the caller cannot be set from outside the route, and a header usually can. Name that property here, and let authentication decide who the caller is. There is a convention worth following rather than inventing one: Taking the object from a header is a different matter and is entirely normal: the caller is entitled to say which resource it wants, and the check is what decides whether it may have it. |
Usage
As a producer, deciding with a filter
The check operation records the verdict in the CamelOpenFgaAllowed header and leaves the message body untouched, so the route decides what to do with it:
-
Java
-
YAML
from("platform-http:/documents")
.to("openfga:check?storeId={{fga.store}}&authorizationModelId={{fga.model}}"
+ "&relation=reader&user=user:${exchangeProperty.CamelKeycloakTokenSubject}"
+ "&object=document:${header.documentId}")
.choice()
.when(header("CamelOpenFgaAllowed").isEqualTo(true))
.to("direct:serveDocument")
.otherwise()
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(403)); - route:
from:
uri: platform-http:/documents
steps:
- to:
uri: openfga:check
parameters:
storeId: "{{fga.store}}"
authorizationModelId: "{{fga.model}}"
relation: reader
user: "user:${exchangeProperty.CamelKeycloakTokenSubject}"
object: "document:${header.documentId}"
- choice:
when:
- expression:
simple:
expression: "${header.CamelOpenFgaAllowed} == true"
steps:
- to:
uri: direct:serveDocument
otherwise:
steps:
- setHeader:
name: CamelHttpResponseCode
expression:
constant:
expression: "403" As a security policy, stopping the route
OpenFgaSecurityPolicy is an AuthorizationPolicy, so the check guards a section of the route and a denial throws CamelAuthorizationException for the usual onException machinery to handle:
-
Java
-
YAML
OpenFgaSecurityPolicy policy = new OpenFgaSecurityPolicy();
policy.setApiUrl("http://openfga:8080");
policy.setStoreId("01HQMVAJ...");
policy.setAuthorizationModelId("01HQMVAK...");
policy.setRelation("writer");
policy.setUser("user:${exchangeProperty.CamelKeycloakTokenSubject}");
policy.setObject("document:${header.documentId}");
from("platform-http:/documents")
.policy(policy)
.to("direct:updateDocument"); - beans:
- name: documentWriters
type: org.apache.camel.component.openfga.security.OpenFgaSecurityPolicy
properties:
apiUrl: http://openfga:8080
storeId: "01HQMVAJ..."
authorizationModelId: "01HQMVAK..."
relation: writer
user: "user:${exchangeProperty.CamelKeycloakTokenSubject}"
object: "document:${header.documentId}"
- route:
from:
uri: platform-http:/documents
steps:
- policy:
ref: documentWriters
steps:
- to:
uri: direct:updateDocument Filtering a collection
batchCheck takes the object identifiers from the body and replaces it with the ones the check allowed, in the order the body asked in:
from("direct:listDocuments")
.to("sql:SELECT id FROM documents")
// sql: answers with a List<Map>, one entry per row, so turn it into the object identifiers first - a Map
// would stringify to {ID=budget}, which is not an identifier and would simply be skipped
.process(exchange -> {
List<Map<String, Object>> rows = exchange.getMessage().getBody(List.class);
exchange.getMessage().setBody(rows.stream().map(row -> "document:" + row.get("id")).toList());
})
.to("openfga:batchCheck?storeId={{fga.store}}&relation=reader"
+ "&user=user:${exchangeProperty.CamelKeycloakTokenSubject}")
.to("direct:render"); The body comes back holding only the identifiers the check allowed, in the order it was given them.
By default, batchCheckMode=client sends one Check request per object, with at most maxParallelRequests (default 10) in flight. This is compatible with older OpenFGA servers.
For OpenFGA 1.8.0 or later, set batchCheckMode=server to use the native BatchCheck API. The SDK groups checks into HTTP requests containing at most maxBatchSize checks (default 50, configurable from 1 to 50; 50 is the default per-request limit of an OpenFGA server, max-checks-per-batch-check, and the component does not go above it even when a server is configured to accept more), and sends at most maxParallelRequests of those requests concurrently. Results are correlated back to their input positions, preserving order and duplicate identifiers even when the server returns answers out of order. For example:
.to("openfga:batchCheck?storeId={{fga.store}}&relation=reader&user=user:anne"
+ "&batchCheckMode=server&maxBatchSize=50&maxParallelRequests=2") The bounded wait accounts for the number of HTTP-request waves in the selected mode. An item error, an incomplete response, or a failed request fails the entire filter, including when failOpen=true; server mode does not silently fall back to client mode. SDK request retries remain governed by maxRetries.
listObjects answers the same question from the other end — ask OpenFGA which objects the subject can reach, rather than filtering a list you already have:
-
Java
-
YAML
to("openfga:listObjects?storeId={{fga.store}}&relation=reader"
+ "&user=user:${exchangeProperty.CamelKeycloakTokenSubject}&type=document");
// body becomes [document:budget, document:roadmap] - route:
from:
uri: direct:myDocuments
steps:
# the body becomes [document:budget, document:roadmap]
- to:
uri: openfga:listObjects
parameters:
storeId: "{{fga.store}}"
relation: reader
user: "user:${exchangeProperty.CamelKeycloakTokenSubject}"
type: document listRelations and listUsers round this out: what a subject may do with one object, and who may do something with it. Both replace the body with a List<String>.
Streaming object queries
streamedListObjects uses OpenFGA’s streamed object query and returns an OpenFgaObjectIterator, implementing Iterator<String> and java.io.Closeable. It opens the response lazily on first iteration and reads as the caller advances, without collecting the full result list or adding a producer queue. A bounded reader buffer provides pull backpressure. Ordinary listObjects still returns a complete list; neither operation offers continuation-token pagination.
Use a streaming splitter to process each object incrementally:
-
Java
-
YAML
from("direct:enumerate")
.to("openfga:streamedListObjects?storeId={{fga.store}}"
+ "&authorizationModelId={{fga.model}}&relation=reader"
+ "&user=user:${exchangeProperty.subject}&type=document")
.split(body()).streaming()
.to("direct:processObject")
.end(); - route:
from:
uri: direct:enumerate
steps:
- to:
uri: openfga:streamedListObjects
parameters:
storeId: "{{fga.store}}"
authorizationModelId: "{{fga.model}}"
relation: reader
user: "user:${exchangeProperty.subject}"
type: document
- split:
simple: "${body}"
streaming: true
steps:
- to:
uri: direct:processObject For ProducerTemplate.requestBody, consume the returned OpenFgaObjectIterator in a try-with-resources block. It remains usable after the exchange completes. Always close it when abandoning iteration. The streaming splitter closes a Closeable iterator; exhaustion, failure and producer stop also close the response.
isComplete() becomes true only after iteration observes the end of the response. Closing early leaves it false. Server errors, malformed records, timeouts and connection errors throw from hasNext() or next(), including after earlier objects have been delivered. Treat those earlier objects as partial results. failOpen does not suppress streaming query failures. The component does not retry this stream automatically, because replay could repeat objects already delivered.
streamMaxResults defaults to 10000 and fails iteration if another object arrives; it never silently truncates the answer. streamMaxLineLength defaults to 65536 characters and bounds one JSON record. Both must be positive. readTimeout bounds waiting for response headers and each blocking attempt to read the next record; it does not limit time spent processing an object between calls. Closing the iterator cancels an in-flight request and closes an active response body.
The operation preserves authorizationModelId, consistency, conditionContext and configured contextual tuples. With the component-created client it uses the SDK’s authentication, serialization and TLS configuration. SDK 0.11 does not expose a cancellable response-body handle from an injected OpenFgaClient. Therefore an injected SDK client requires an explicit streamingClient implementing OpenFgaStreamingClient, plus storeId and a positive readTimeout. This SPI must return the actual cancellable request future and its closeable response body; the application owns the SPI client’s lifecycle. Endpoint credentials are not used to guess the configuration of an injected SDK client.
Granting and revoking access
A route that creates a resource usually has to grant access to it too. writeTuples takes its tuple from the endpoint’s user/relation/object when they are configured, and from the body only when none of them is — the configured tuple is the shape that reads best right after a resource was created:
-
Java
-
YAML
from("direct:createDocument")
.to("sql:INSERT INTO documents ...")
.to("openfga:writeTuples?storeId={{fga.store}}"
+ "&user=user:${exchangeProperty.CamelKeycloakTokenSubject}&relation=owner"
+ "&object=document:${header.documentId}"); - route:
from:
uri: direct:createDocument
steps:
- to:
uri: "sql:INSERT INTO documents ..."
- to:
uri: openfga:writeTuples
parameters:
storeId: "{{fga.store}}"
user: "user:${exchangeProperty.CamelKeycloakTokenSubject}"
relation: owner
object: "document:${header.documentId}" For several tuples at once, leave user/relation/object unset and put them in the body instead — a collection of Map`s with `user, relation and object entries, or of ClientTupleKey objects. deleteTuples accepts the same shapes and revokes instead.
A writeTuples body may also set a relationship condition on a tuple: a ClientTupleKey built with .condition(..), or a Map whose condition entry is itself a map of a name and an optional context. The condition is written through as given, so a conditioned grant stays conditioned; a tuple with no condition is written unconditioned. Because a condition can ride only on the body, a tuple configured on the endpoint is always written without one; set the condition on the body when you need a conditioned tuple. A deleteTuples body may carry a condition too, but it is ignored, because OpenFGA deletes by identity.
| The endpoint wins over the body If the endpoint configures any of The same rule that governs a check governs a write: the configuration decides and the message does not. Were the body preferred, a route that unmarshals an untrusted payload before writing would hand the caller the choice of which relationship to grant — and A partly configured triple is treated as a mistake rather than an invitation to fill the rest in from the message: the producer fails and names the part that is missing. |
A typed wildcard — user:*, OpenFGA’s "everyone" — is accepted here, because writing that tuple is how a resource is shared publicly and is a deliberate act by the route. It is refused as the subject of a check; see below.
Mutation conflicts and atomic updates
By default, onDuplicate=error makes an existing relationship fail a write, and onMissing=error makes an absent relationship fail a delete. On OpenFGA 1.10.0 or later, select onDuplicate=ignore or onMissing=ignore explicitly for reconciliation routes that should leave an already-satisfied operation unchanged. These options apply to writeTuples and deleteTuples, respectively, and both apply to write.
Use write to grant and revoke relationships in one atomic request. With no configured user/relation/object, the body is a Map containing writes and/or deletes collections. Each entry is an ordinary Map with user, relation and object; a timestamp entry, as readTuples returns it, is ignored, so a page of readTuples can be revoked as it is. A condition entry is written through on a write and ignored on a delete. Other body shapes or entry fields are rejected. For example:
Map<String, Object> changes = Map.of(
"writes", List.of(Map.of("user", "user:anne", "relation", "writer", "object", "document:budget")),
"deletes", List.of(Map.of("user", "user:anne", "relation", "reader", "object", "document:budget")));
template.requestBody("openfga:write?storeId={{fga.store}}&authorizationModelId={{fga.model}}", changes); The component requires at least one tuple and rejects an all-empty write, and the sum of writes and deletes cannot exceed 100. It rejects larger transactions before calling OpenFGA and never splits this atomic update into independently committed requests. A failed transaction remains a failure even when failOpen=true. The component applies an endpoint-configured model revision to the transaction. A server configured with a lower tuple limit can reject a request within the component’s limit.
The configured-tuple precedence also applies to write: when any of user/relation/object is configured, that triple supplies one write, the body is ignored, and no deletes are taken from it. A missing configured part fails rather than falling back to the body.
Successful mutations preserve the input body. CamelOpenFgaWrittenTuples and CamelOpenFgaDeletedTuples report the number of submitted operations, including any that the selected ignore mode skipped; they do not report the number of rows changed in storage. The combined write operation sets both counters, including zero for an omitted side.
Security
It fails closed
An OpenFGA server that cannot be reached, or that answers with an error, denies. The failOpen option reverses that and is off by default; it is marked insecure:dev and should not be enabled in production.
failOpen covers only a failure to obtain an answer, and only for check and for OpenFgaSecurityPolicy — the two places where "proceed" means something. It never turns a denial into an allow, and it never applies to an Exchange that carried no usable subject (see below).
When failOpen does let an exchange through, it carries CamelOpenFgaFailedOpen=true. The verdict header alone cannot distinguish "OpenFGA allowed this" from "OpenFGA was never reached and we were told to proceed", and an audit asking which exchanges went through unauthorized needs something it can filter on. The marker is set only on that deliberate path, and it is cleared on entry like the other decision headers so a sender cannot preload it.
It also does not apply when OpenFGA answers with an HTTP 4xx. A 400 means the question was malformed, a 401 or 403 that this client may not ask it, a 404 that what was asked about does not exist — none of which is a decision point that has gone away. This matters concretely: an object identifier can get past the component’s own guards and still be rejected by the server (document:a:b and document:x#y are both HTTP 400 on OpenFGA 1.21.0), and if failOpen covered that, any caller able to influence the identifier could turn a check into an allow. Those fail closed, and the component logs why it did not fail open. A 429 is the one 4xx that does count as unavailable — it means "not right now" — as do transport errors, timeouts and 5xx.
The rule is an allowlist rather than a list of exclusions: failOpen applies to a rate limit, a 5xx, a transport error and a timeout, and to nothing else. A failure the component does not recognise — a request the SDK refused to build, input it could not serialise, an interrupt during shutdown — is not evidence that OpenFGA was unreachable, so it denies. Anything unfamiliar therefore fails closed rather than being waved through for being unfamiliar.
The query operations ignore failOpen entirely: a batchCheck or listObjects that failed has no safe way to proceed, since handing back the objects it never managed to filter would be exactly the leak the filtering was there to prevent.
What is asked is not up to the message
storeId, authorizationModelId, relation and the operation all come from the endpoint. An inbound message cannot point the check at a different store, pin an older model revision, downgrade the relation demanded from owner to reader, or turn a check into a tuple write.
The CamelOpenFga* headers are outputs only. They are cleared on entry — before the expressions are evaluated — written on every evaluation, and never read back as inputs, so a verdict a message arrived with never survives into the route, including down the paths that throw.
A missing identity is a denial, not a failure
If the user or object expression resolves to blank — or to a bare user: prefix, which is what a configured prefix plus an unresolved expression leaves behind — the Exchange is denied with CamelOpenFgaDenyReason set to missing-user or missing-object, and OpenFGA is never asked.
This split matters. OpenFGA would reject a blank subject with an HTTP 400, which is a failure to obtain a verdict — and with failOpen set a failure becomes an allow. An Exchange that carried no identity has not been authorized by anything, so it is denied, and failOpen does not reach it.
A wildcard subject is refused
user:* is a legitimate thing to write a tuple for. It is not a legitimate thing to check: asking "may everyone read this" is not asking whether the caller may, and OpenFGA answers true for it wherever a public-access tuple exists. A user expression that resolved to a typed wildcard would therefore hand out every publicly shared object, so it is denied with CamelOpenFgaDenyReason set to wildcard-subject.
Pin the authorization model
authorizationModelId is optional, and leaving it out means "whichever model the store considers latest". A store keeps every model it was ever given and "latest" moves the moment somebody writes a new one, so an unpinned endpoint can start answering a different question than the one it was reviewed with — with no change to the route. The component logs a warning at startup when it is unset. Pin it in production, so that a model rollout is a deliberate, reviewable configuration change.
Consistency
OpenFGA’s default read consistency may answer from a replica that has not caught up, which right after a revoke means a deleted tuple can still grant access for a moment. Set consistency=HIGHER_CONSISTENCY on the paths where that window matters, at the cost of latency.
The value is checked when the endpoint starts, and an unrecognised one — higher_consistency, say — is refused rather than accepted and quietly sent as unknown_default_open_api on every request.
Authentication and TLS
For a server started with --authn-method preshared, set apiToken. For one behind an OIDC provider, set clientId, clientSecret, apiTokenIssuer and apiAudience for the OAuth 2.0 client-credentials flow. Both apiToken and clientSecret are marked secret and are masked wherever Camel prints an endpoint URI.
sslContextParameters configures TLS, including presenting a client certificate to a server that requires mutual TLS. A SPIFFE X.509-SVID obtained through camel-spiffe works here, which closes the loop: the workload authenticates to the authorization decision point as itself.
useGlobalSslContextParameters on the component does not reach OpenFgaSecurityPolicy, which is a bean rather than an endpoint of the component. Set useGlobalSslContextParameters, or sslContextParameters, on the policy itself. |
Timeouts
connectTimeout and readTimeout bound the call, and maxRetries bounds how often a retryable failure is re-attempted. The component supplies the SDK’s HTTP client itself so that connectTimeout actually takes effect; the SDK’s own connectTimeout setting is accepted and then never read, and the client it builds by default sets none, leaving the connect phase bounded only by the operating system.
Health checks
Each check owns its HTTP client and releases it when the check stops. The five-second health deadline includes the complete response body; a stalled body reports DOWN and the outstanding request is cancelled.
Both the producer and OpenFgaSecurityPolicy register a readiness check that probes OpenFGA’s /healthz endpoint. Because the component fails closed, a route that is up but cannot reach OpenFGA fails every message, so it is not ready — and this makes that visible before traffic arrives rather than only in the error logs afterwards.
The check requires the server to report SERVING, not merely to answer with HTTP 200: the HTTP gateway can answer 200 while the health service behind it reports NOT_SERVING.
No check is registered for an injected openFgaClient, which can point anywhere the component has no way to ask about. Set healthCheckProducerEnabled=false on the component, or healthCheckEnabled=false on the policy, to turn them off.
Contextual tuples and condition context
contextualTuples hands OpenFGA relationships that are true for one request and never stored — a group membership that lives in the token rather than in the graph, or a fact about the request such as which network it arrived on. It takes semicolon-separated user,relation,object triples, each part a Simple expression:
-
Java
-
YAML
// both the subject and the team come from exchange properties the route's own token-validating step set.
// the object may come from the request - asking about a document is the caller's prerogative - but the
// granting tuple must not, which is what the IMPORTANT block below is about
to("openfga:check?storeId={{fga.store}}&relation=reader"
+ "&user=user:${exchangeProperty.CamelKeycloakTokenSubject}"
+ "&object=document:${header.documentId}"
+ "&contextualTuples=user:${exchangeProperty.CamelKeycloakTokenSubject},member,"
+ "team:${exchangeProperty.tokenTeam}"); - route:
from:
uri: direct:checkWithTeam
steps:
- to:
uri: openfga:check
parameters:
storeId: "{{fga.store}}"
relation: reader
user: "user:${exchangeProperty.CamelKeycloakTokenSubject}"
object: "document:${header.documentId}"
contextualTuples: "user:${exchangeProperty.CamelKeycloakTokenSubject},member,team:${exchangeProperty.tokenTeam}" It applies to check, batchCheck, listObjects, streamedListObjects, listRelations and listUsers. On batchCheck the context goes on every item in either client or server mode, so each object is judged against the same facts.
OpenFgaSecurityPolicy takes both options as well, through setContextualTuples and setConditionContext. They are no more dangerous on the policy than on an endpoint and no less: either way the value comes from whoever configured the route, never from the message.
| A comma inside a Simple expression The option is split on |
conditionContext supplies the values that any conditioned relation’s CEL expression is evaluated with, as a map resolved from the registry — conditionContext=#myContext. A map rather than an expression on purpose: OpenFGA types every condition parameter in the authorization model (int, bool, timestamp, ipaddress), and a map lets you supply the right Java type instead of a string the server would reject.
YAML, like a properties file, hands every value over as a string, the entries of a map included. OpenFGA converts a string for an int, uint, double, duration, timestamp or ipaddress parameter, so those can be written as they are, but it rejects one for a bool parameter: give that as #valueAs(boolean):true. A list or map parameter cannot be written inline at all; declare it as a bean of its own and refer to it with #bean::
-
Java
-
YAML
Map<String, Object> networkContext = Map.of(
"trusted", true,
"allowed_regions", List.of("eu", "us"));
context.getRegistry().bind("networkContext", networkContext);
from("direct:checkFromTrustedNetwork")
.to("openfga:check?storeId={{fga.store}}&relation=reader"
+ "&user=user:${exchangeProperty.CamelKeycloakTokenSubject}"
+ "&object=document:${header.documentId}&conditionContext=#networkContext"); - beans:
- name: allowedRegions
type: java.util.ArrayList
properties:
"0": eu
"1": us
- name: networkContext
type: java.util.LinkedHashMap
properties:
# a bool parameter needs a boolean: the string "true" is rejected
trusted: "#valueAs(boolean):true"
# a list parameter needs a list
allowed_regions: "#bean:allowedRegions"
- route:
from:
uri: direct:checkFromTrustedNetwork
steps:
- to:
uri: openfga:check
parameters:
storeId: "{{fga.store}}"
relation: reader
user: "user:${exchangeProperty.CamelKeycloakTokenSubject}"
object: "document:${header.documentId}"
conditionContext: "#networkContext" OpenFgaSecurityPolicy also takes the map inline, under the same rules:
- beans:
- name: documentReaders
type: org.apache.camel.component.openfga.security.OpenFgaSecurityPolicy
properties:
storeId: "{{fga.store}}"
relation: reader
user: "user:${exchangeProperty.CamelKeycloakTokenSubject}"
object: "document:${header.documentId}"
conditionContext:
trusted: "#valueAs(boolean):true"
max_amount: 100 A value of the wrong type fails the check with an HTTP 400 from OpenFGA, naming the parameter it could not convert. That is an answer rather than an unavailable decision point, so the exchange is refused even when failOpen is set.
| A contextual tuple grants A contextual tuple is read exactly like a stored one. That is why both options are endpoint-only and are never read from the message. A contextual tuple the caller could choose would let it assert the very relationship being checked, which is the whole decision. The same reasoning applies to a condition context, because a condition can decide a relation. It follows that an expression here which reads an inbound header hands the caller that power anyway. Keep these literal, or derive them from something the route established — the same rule as for A part that resolves to blank denies the exchange with |
Contextual tuples supplied by the message are deliberately not supported. If you need them, the tuple has to come from somewhere the caller cannot reach, which in practice means the endpoint.
Reading the graph
readTuples answers "what access exists", as opposed to check’s "may this subject do this". Here `user, relation and object are a filter rather than a subject, and the body comes back as a list of maps keyed user, relation, object and timestamp, plus a condition map of name and context when the stored tuple has one — deliberately the keys writeTuples and deleteTuples accept, so a route can revoke what it just read, or re-grant it with its condition intact, without reshaping anything:
-
Java
-
YAML
from("direct:revokeEverythingBobHas")
.to("openfga:readTuples?storeId={{fga.store}}&object=document:&user=user:bob")
.to("openfga:deleteTuples?storeId={{fga.store}}"); - route:
from:
uri: direct:revokeEverythingBobHas
steps:
- to:
uri: openfga:readTuples
parameters:
storeId: "{{fga.store}}"
object: "document:"
user: "user:bob"
- to:
uri: openfga:deleteTuples
parameters:
storeId: "{{fga.store}}" | What OpenFGA accepts as a read filter The filter is narrower than "every part is optional". Measured against OpenFGA 1.21.0:
The component checks this before the call and names the option to change, rather than letting an opaque HTTP 400 through. Note this is also why a type-only What "optional" does not mean is that a part may go missing at runtime. Only an option the endpoint never set counts as "do not filter on this"; an option that is set and evaluates to nothing — |
readChanges reads the change log, which is the building block for keeping a cache or a projection in step with the graph. Each entry adds an operation of WRITE or DELETE, and carries the same condition map as readTuples when the changed tuple has one.
Both are paged. pageSize bounds one request, and the token the page returns arrives on CamelOpenFgaContinuationToken; feed it back through continuationToken to read on.
Consuming the change log with durable checkpoints
Only readChanges supports consumption. It polls one bounded page per scheduled poll and sends a List<Map<String, Object>> containing the changes, in server order, to the route. Configure pageSize to bound the requested page size; empty tail pages do not produce exchanges. Standard scheduled polling options, such as delay, initialDelay and polling backoff, control the schedule.
Register an application-provided org.apache.camel.spi.StateRepository<String, String> as changeCheckpoints. A repository that is a Camel service, such as FileStateRepository, is started by the consumer when the application has not started it, and stopped again when the route stops; a repository the application started stays under the application’s control. A repository that several routes share, each with its own checkpointKey, should be started and stopped by the application: otherwise the first route to start owns it and stops it with that route, and a stopped FileStateRepository answers null to the other routes, which then start again from startTime or the beginning:
-
Java
-
YAML
from("openfga:readChanges?storeId={{fga.store}}&type=document"
+ "&checkpointRepository=#changeCheckpoints&checkpointKey=documents-projection-v1"
+ "&pageSize=100&delay=1000&changePollTimeout=30000")
.split(body()).shareUnitOfWork().stopOnException()
.to("direct:applyChange")
.end(); - route:
from:
uri: openfga:readChanges
parameters:
storeId: "{{fga.store}}"
type: document
checkpointRepository: "#changeCheckpoints"
checkpointKey: documents-projection-v1
pageSize: 100
delay: 1000
changePollTimeout: 30000
steps:
- split:
expression:
simple:
expression: "${body}"
shareUnitOfWork: true
stopOnException: true
steps:
- to:
uri: direct:applyChange Both checkpointRepository and checkpointKey are required. Implement the repository with durable storage: getState(key) returns the last committed cursor or null, and setState(key, cursor) must atomically persist it before returning. A failed store must preserve the previous value. Repository methods must impose finite I/O deadlines. Camel does not substitute an in-memory repository and does not own the repository’s lifecycle. Reuse a state repository only when it meets these durability and failure requirements; an in-memory repository cannot resume after a process restart.
Choose a stable key unique to the server, store, type filter and projection. Exactly one active consumer may own a key; the SPI does not provide distributed leader election. For clustered deployments, consider master to run one active route. A component-level checkpoint key must still be unique for every consumer. Use a different key when deliberately rebuilding a projection or changing its filter. continuationToken is not accepted on a consumer; the durable repository is its only cursor source. startTime applies only before a cursor exists and must remain consistent across restarts.
After the whole page succeeds, the consumer durably stores its next token. A route exception or rollback leaves the checkpoint unchanged. A handled route exception counts as successful processing, so do not mark an incomplete projection as handled. With a splitter, propagate failure to the parent page as in the example. Avoid fire-and-forget processing when the checkpoint must cover the resulting work.
Delivery is at least once. A crash after applying changes but before storing the checkpoint, a failed checkpoint write, or shutdown during page processing can repeat the complete page on the next poll or restart. Make projection updates idempotent. The checkpoint and downstream side effects do not form one atomic transaction. Ordering is preserved within each server page and between polls of a single consumer; parallel route processing can change application order.
The repository is reloaded on each poll. An empty tail page retains an echoed cursor, an advanced empty-page cursor is stored, and a missing token never erases the existing bookmark. Read failures, including expired or invalid server cursors, are reported through the polling error handler; they never silently restart at the beginning. Cursor validity and retained history depend on the OpenFGA server and its storage configuration. Plan recovery or a projection rebuild when the server can no longer resume a bookmark; checkpoints cannot guarantee indefinite replay.
changePollTimeout bounds awaiting the page request and cancels it on expiry. Stopping the consumer cancels a pending request and prevents acknowledging an unfinished page. SDK request timeouts still apply. Route processing and repository calls must cooperate with Camel shutdown and their own deadlines; the consumer does not forcibly interrupt arbitrary application code. failOpen does not suppress polling or checkpoint failures.
The readChanges producer remains available for manual polling. Its caller owns cursor persistence and must save the returned CamelOpenFgaContinuationToken only after successfully processing the complete page. An exchange property or global variable is not a durable checkpoint across restarts.
startTime bounds where a first read begins — without it a first readChanges on a busy store pages through the whole history before reaching anything current.
| The two read operations signal "done" differently Measured against OpenFGA 1.21.0, not assumed:
|
expand is the odd one out: it is the only operation that does not leave a List on the body, because its answer is a tree of usersets rather than a list. The UsersetTree goes on the body as the SDK returns it — flattening it is exactly what would destroy the information the operation exists to provide. Reach for it when a check answered something surprising and you need to see how it got there.
What this component does not do yet
-
Store and authorization-model management —
createStore,deleteStore,writeAuthorizationModeland the rest. These are administrative rather than integration operations, and a component that can delete the store it authorizes against is a different proposition from one that can only ask it questions.
Examples
Guarding an HTTP endpoint, with the identity coming from an authentication step earlier in the route:
-
Java
-
YAML
from("platform-http:/orders/{orderId}")
// whatever verifies the caller, ending in a processor that records the verified subject as a property
.to("direct:authenticate")
.to("openfga:check?storeId={{fga.store}}&authorizationModelId={{fga.model}}"
+ "&relation=can_view&user=user:${exchangeProperty.CamelKeycloakTokenSubject}"
+ "&object=order:${header.orderId}")
.filter(header("CamelOpenFgaAllowed").isEqualTo(true))
.to("direct:serveOrder"); - route:
from:
uri: "platform-http:/orders/{orderId}"
steps:
# whatever verifies the caller, ending in a step that records the verified subject as a property
- to:
uri: direct:authenticate
- to:
uri: openfga:check
parameters:
storeId: "{{fga.store}}"
authorizationModelId: "{{fga.model}}"
relation: can_view
user: "user:${exchangeProperty.CamelKeycloakTokenSubject}"
object: "order:${header.orderId}"
- filter:
expression:
simple:
expression: "${header.CamelOpenFgaAllowed} == true"
steps:
- to:
uri: direct:serveOrder Authorization observations
See Authorization observations for optional decision events, low-cardinality metrics and verified-identity composition examples. Observations preserve the component’s existing decision headers and error handling.