Keycloak
Since Camel 4.15
Both producer and consumer are supported
The Keycloak component supports running operations on Keycloak instance and policy enforcements.
Component Features
The Keycloak component provides three main functionalities:
-
Producer Operations - Manage Keycloak instances via the Admin API (realms, users, roles, clients, groups, sessions, tokens, and more)
-
Consumer Operations - Poll and consume user events and admin events from Keycloak for monitoring, auditing, and event-driven workflows
-
Security Policies - Route-level authorization using Keycloak authentication and authorization services, including role-based access, permission-based access, and OAuth 2.0 token introspection
URI Format
keycloak://label[?options]
You can append query options to the URI in the following format:
?options=value&option2=value&…
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 Keycloak component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
An access token the admin client sends as the Bearer token of its requests, instead of signing in with username and password or with the client credentials. It is used as is and not refreshed, so the calls fail once it expires. | String | ||
Only the admin events made through the client with this ID (the internal ID of the client, not its client ID). Used with eventType=admin-events. | String | ||
Only the admin events made from this IP address. Used with eventType=admin-events. | String | ||
The realm the admin client signs in to. If not set, the realm option is used. Set it to sign in to one realm, such as master, and manage another. | master | String | |
Only the admin events made by a caller signed in to the realm with this ID (the realm ID, which can differ from the realm name). Used with eventType=admin-events. | String | ||
Only the admin events made by the user with this user ID. Used with eventType=admin-events. | String | ||
Only the user events of the client with this client ID. Used with eventType=events. | String | ||
The client ID to authenticate with. With clientSecret, the admin client signs in with the client credentials grant, when neither accessToken nor username and password are set. revokeAccessToken, revokeRefreshToken, introspectToken and evaluatePermission always authenticate with clientId and clientSecret. | String | ||
The secret of the client set in clientId. | String | ||
Component configuration. | KeycloakConfiguration | ||
Only the events from this date on: a date in the yyyy-MM-dd format, or, with a Keycloak server version that supports it, a time in milliseconds since the epoch. Used with both event types. | String | ||
Only the events up to this date, inclusive, in the same formats as dateFrom. Used with both event types. | String | ||
The type of events the consumer reads: events, for user events such as LOGIN, or admin-events, for the changes made through the Admin API or the Admin Console. | events | String | |
The index of the first event each poll reads. Keycloak returns the newest events first, so a value above 0 leaves out that many of the newest events. | 0 | int | |
Not used by this endpoint: introspectToken does not cache its results. Caching of introspection results is set on KeycloakSecurityPolicy. | true | boolean | |
Not used by this endpoint, see introspectionCacheEnabled. | 60 | long | |
Only the user events from this IP address. Used with eventType=events. | String | ||
Autowired An existing Keycloak admin client (org.keycloak.admin.client.Keycloak) to use. When set, the endpoint does not build its own admin client from serverUrl, authRealm and the credentials, and does not close it when it stops. revokeAccessToken, revokeRefreshToken, introspectToken and evaluatePermission still call serverUrl with clientId and clientSecret. | Keycloak | ||
The number of events the first poll retrieves, and the page size of the later polls, which read every event since the previous poll. | 100 | int | |
The operation to perform. Enum values:
| KeycloakOperations | ||
Only the admin events of these operation types, as a comma-separated list of CREATE, UPDATE, DELETE and ACTION. Used with eventType=admin-events. | String | ||
The password of the user set in username. | String | ||
Whether the create and update operations take the Keycloak representation to send, such as a UserRepresentation for createUser, from the message body; a Map or JSON text of it is converted. Otherwise they build it from headers, and the operations that need a full representation, such as updateRealm and createResource, fail. | false | boolean | |
The realm the consumer reads events from, and the realm the admin client signs in to unless authRealm is set. Most producer operations take the realm from the CamelKeycloakRealmName header instead: revokeAccessToken, revokeRefreshToken and introspectToken use this option when the header is not set, and evaluatePermission always uses it. | master | String | |
Only the admin events on this resource path, such as users/*, where * matches any characters. Used with eventType=admin-events. | String | ||
The base URL of the Keycloak server, for example http://localhost:8080. Required unless keycloakClient is set. | String | ||
Only the user events of these types, as a comma-separated list such as LOGIN,LOGOUT. Used with eventType=events. | String | ||
Only the user events of the user with this user ID. Used with eventType=events. | String | ||
The username the admin client signs in with, together with password, through the admin-cli client (password grant), when accessToken is not set. evaluatePermission also uses username and password when the CamelKeycloakAccessToken header is not set. | String | ||
Not used by this endpoint: no operation of the endpoint validates tokens, and introspectToken always calls the token introspection endpoint of Keycloak. Token introspection for routes is set on KeycloakSecurityPolicy. | 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 | |
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 | |
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 | |
Whether the CamelKeycloakOperation header may override the configured operation. Disabled by default: the operation decides what the endpoint does with its admin client, from reading a user to deleting a realm, so a message that can set the header can run any operation that the credentials of the endpoint allow. Enable it only on routes whose input is trusted. | false | boolean |
Endpoint Options
The Keycloak endpoint is configured using URI syntax:
keycloak:label
With the following path and query parameters:
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
An access token the admin client sends as the Bearer token of its requests, instead of signing in with username and password or with the client credentials. It is used as is and not refreshed, so the calls fail once it expires. | String | ||
Only the admin events made through the client with this ID (the internal ID of the client, not its client ID). Used with eventType=admin-events. | String | ||
Only the admin events made from this IP address. Used with eventType=admin-events. | String | ||
The realm the admin client signs in to. If not set, the realm option is used. Set it to sign in to one realm, such as master, and manage another. | master | String | |
Only the admin events made by a caller signed in to the realm with this ID (the realm ID, which can differ from the realm name). Used with eventType=admin-events. | String | ||
Only the admin events made by the user with this user ID. Used with eventType=admin-events. | String | ||
Only the user events of the client with this client ID. Used with eventType=events. | String | ||
The client ID to authenticate with. With clientSecret, the admin client signs in with the client credentials grant, when neither accessToken nor username and password are set. revokeAccessToken, revokeRefreshToken, introspectToken and evaluatePermission always authenticate with clientId and clientSecret. | String | ||
The secret of the client set in clientId. | String | ||
Only the events from this date on: a date in the yyyy-MM-dd format, or, with a Keycloak server version that supports it, a time in milliseconds since the epoch. Used with both event types. | String | ||
Only the events up to this date, inclusive, in the same formats as dateFrom. Used with both event types. | String | ||
The type of events the consumer reads: events, for user events such as LOGIN, or admin-events, for the changes made through the Admin API or the Admin Console. | events | String | |
The index of the first event each poll reads. Keycloak returns the newest events first, so a value above 0 leaves out that many of the newest events. | 0 | int | |
Not used by this endpoint: introspectToken does not cache its results. Caching of introspection results is set on KeycloakSecurityPolicy. | true | boolean | |
Not used by this endpoint, see introspectionCacheEnabled. | 60 | long | |
Only the user events from this IP address. Used with eventType=events. | String | ||
Autowired An existing Keycloak admin client (org.keycloak.admin.client.Keycloak) to use. When set, the endpoint does not build its own admin client from serverUrl, authRealm and the credentials, and does not close it when it stops. revokeAccessToken, revokeRefreshToken, introspectToken and evaluatePermission still call serverUrl with clientId and clientSecret. | Keycloak | ||
The number of events the first poll retrieves, and the page size of the later polls, which read every event since the previous poll. | 100 | int | |
The operation to perform. Enum values:
| KeycloakOperations | ||
Only the admin events of these operation types, as a comma-separated list of CREATE, UPDATE, DELETE and ACTION. Used with eventType=admin-events. | String | ||
The password of the user set in username. | String | ||
Whether the create and update operations take the Keycloak representation to send, such as a UserRepresentation for createUser, from the message body; a Map or JSON text of it is converted. Otherwise they build it from headers, and the operations that need a full representation, such as updateRealm and createResource, fail. | false | boolean | |
The realm the consumer reads events from, and the realm the admin client signs in to unless authRealm is set. Most producer operations take the realm from the CamelKeycloakRealmName header instead: revokeAccessToken, revokeRefreshToken and introspectToken use this option when the header is not set, and evaluatePermission always uses it. | master | String | |
Only the admin events on this resource path, such as users/*, where * matches any characters. Used with eventType=admin-events. | String | ||
The base URL of the Keycloak server, for example http://localhost:8080. Required unless keycloakClient is set. | String | ||
Only the user events of these types, as a comma-separated list such as LOGIN,LOGOUT. Used with eventType=events. | String | ||
Only the user events of the user with this user ID. Used with eventType=events. | String | ||
The username the admin client signs in with, together with password, through the admin-cli client (password grant), when accessToken is not set. evaluatePermission also uses username and password when the CamelKeycloakAccessToken header is not set. | String | ||
Not used by this endpoint: no operation of the endpoint validates tokens, and introspectToken always calls the token introspection endpoint of Keycloak. Token introspection for routes is set on KeycloakSecurityPolicy. | false | boolean | |
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 | |
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 | |
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 | |
Whether the CamelKeycloakOperation header may override the configured operation. Disabled by default: the operation decides what the endpoint does with its admin client, from reading a user to deleting a realm, so a message that can set the header can run any operation that the credentials of the endpoint allow. Enable it only on routes whose input is trusted. | false | boolean |
Message Headers
The Keycloak component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
CamelKeycloakOperation (common) Constant: | The operation to perform, in place of the operation of the endpoint. Ignored unless the endpoint sets allowOperationHeader=true, because the operation decides what the endpoint does with its admin client, such as deleting a realm. Enum values:
| KeycloakOperations | |
CamelKeycloakRealmName (common) Constant: | The name of the realm. Most producer operations require it, and createRealm names the new realm with it; revokeAccessToken, revokeRefreshToken and introspectToken use the realm option when it is not set. The consumer sets it to the realm of the event. | String | |
| Constant: | The user ID. | String | |
CamelKeycloakUsername (common) Constant: | The username. | String | |
CamelKeycloakUserEmail (common) Constant: | The user email. | String | |
CamelKeycloakUserFirstName (common) Constant: | The user first name. | String | |
CamelKeycloakUserLastName (common) Constant: | The user last name. | String | |
| Constant: | Deprecated The role ID. Deprecation note: Never read by the component: the role operations address a role by its name (CamelKeycloakRoleName). | String | |
CamelKeycloakRoleName (common) Constant: | The role name. | String | |
CamelKeycloakRoleDescription (common) Constant: | The role description. | String | |
| Constant: | The group ID. | String | |
CamelKeycloakGroupName (common) Constant: | The group name. | String | |
CamelKeycloakClientId (common) Constant: | The client ID of the client that createClient creates. | String | |
CamelKeycloakClientUuid (common) Constant: | The internal ID (a UUID) of the client, which the client, client role, client secret and authorization operations use to address the client. | String | |
CamelKeycloakUserPassword (common) Constant: | The user password. | String | |
CamelKeycloakPasswordTemporary (common) Constant: | Whether the password that resetUserPassword sets is temporary, so that the user must change it at the next login. Default false. | Boolean | |
CamelKeycloakSearchQuery (common) Constant: | The text that searchUsers looks for in the username, first name, last name and email of the users. If not set, searchUsers lists all users. | String | |
CamelKeycloakMaxResults (common) Constant: | The maximum number of results of searchUsers, listOrganizations, searchOrganizations and listOrganizationMembers. searchUsers uses it only together with CamelKeycloakFirstResult. | Integer | |
CamelKeycloakFirstResult (common) Constant: | The index of the first result of searchUsers, listOrganizations, searchOrganizations and listOrganizationMembers. searchUsers uses it only together with CamelKeycloakMaxResults. | Integer | |
CamelKeycloakClientScopeId (common) Constant: | The client scope ID. | String | |
CamelKeycloakClientScopeName (common) Constant: | The client scope name. | String | |
CamelKeycloakEventType (common) Constant: | Set by the consumer: event for a user event, or admin-event for an admin event. | String | |
| Constant: | Set by the consumer to the time of the event, in milliseconds since the epoch. | Long | |
CamelKeycloakIdpAlias (common) Constant: | The identity provider alias. | String | |
| Constant: | Deprecated The identity provider ID. Deprecation note: Never read by the component: the identity provider operations address a provider by its alias (CamelKeycloakIdpAlias). | String | |
CamelKeycloakResourceId (common) Constant: | The resource ID. | String | |
CamelKeycloakResourceName (common) Constant: | Deprecated The resource name. Deprecation note: Never read by the component: createResource and updateResource take a ResourceRepresentation as the POJO request body. | String | |
CamelKeycloakResourceType (common) Constant: | Deprecated The resource type. Deprecation note: Never read by the component: createResource and updateResource take a ResourceRepresentation as the POJO request body. | String | |
CamelKeycloakResourceUri (common) Constant: | Deprecated The resource URI. Deprecation note: Never read by the component: createResource and updateResource take a ResourceRepresentation as the POJO request body. | String | |
CamelKeycloakPolicyId (common) Constant: | The policy ID. | String | |
CamelKeycloakPolicyName (common) Constant: | Deprecated The policy name. Deprecation note: Never read by the component: the resource policy operations take a PolicyRepresentation as the POJO request body. | String | |
CamelKeycloakPolicyType (common) Constant: | Deprecated The policy type. Deprecation note: Never read by the component: the resource policy operations take a PolicyRepresentation as the POJO request body. | String | |
CamelKeycloakPermissionId (common) Constant: | The permission ID. | String | |
CamelKeycloakPermissionName (common) Constant: | Deprecated The permission name. Deprecation note: Never read by the component: createResourcePermission takes a ResourcePermissionRepresentation as the POJO request body, and the other permission operations identify the permission with CamelKeycloakPermissionId. | String | |
CamelKeycloakScopeName (common) Constant: | Deprecated The scope name. Deprecation note: Never read by the component: there are no authorization-scope operations, and the client scope operations use CamelKeycloakClientScopeName. | String | |
CamelKeycloakAttributeName (common) Constant: | The user attribute name. | String | |
CamelKeycloakAttributeValue (common) Constant: | The user attribute value. | String | |
CamelKeycloakCredentialId (common) Constant: | The credential ID. | String | |
CamelKeycloakCredentialType (common) Constant: | Deprecated The credential type. Deprecation note: Never read by the component: no credential operation takes a CredentialRepresentation request body. deleteUserCredential uses CamelKeycloakCredentialId, and resetUserPassword builds a password credential from CamelKeycloakUserPassword. | String | |
CamelKeycloakRequiredAction (common) Constant: | The required action, such as UPDATE_PASSWORD or VERIFY_EMAIL, that addRequiredAction adds to the user or removeRequiredAction removes from the user. | String | |
| Constant: | The required actions, such as UPDATE_PASSWORD, that executeActionsEmail asks the user by email to perform. | List | |
CamelKeycloakRedirectUri (common) Constant: | The redirect URI. | String | |
CamelKeycloakLifespan (common) Constant: | The lifespan in seconds. | Integer | |
| Constant: | The users that bulkCreateUsers creates or bulkUpdateUsers updates, as UserRepresentation, Map or JSON text. If not set, a List body is used. | List | |
| Constant: | The IDs of the users for bulkDeleteUsers and bulkAssignRoleToUsers. If not set, CamelKeycloakUsernames is used, and then a List body. | List | |
CamelKeycloakUsernames (common) Constant: | The usernames of the users for bulkDeleteUsers and bulkAssignRoleToUsers, used when CamelKeycloakUserIds is not set. | List | |
CamelKeycloakRoleNames (common) Constant: | The names of the realm roles that bulkAssignRolesToUser assigns to the user. If not set, a List body is used. | List | |
CamelKeycloakContinueOnError (common) Constant: | Whether a bulk operation goes on with the next element when one fails, and lists the failure in its result, instead of failing. Default false. | Boolean | |
CamelKeycloakBatchSize (common) Constant: | Deprecated Batch size for bulk operations. Deprecation note: Never read by the component: the bulk operations send every element of the list one by one, with no batching. | Integer | |
CamelKeycloakAccessToken (common) Constant: | The access token of the caller whose permissions evaluatePermission evaluates. If not set, evaluatePermission signs in with the username and password options, or else with the client credentials. | String | |
| Constant: | The token that revokeAccessToken, revokeRefreshToken or introspectToken works on. If not set, the body is used. | String | |
CamelKeycloakTokenTypeHint (common) Constant: | The token_type_hint that revokeAccessToken and revokeRefreshToken send, access_token or refresh_token. If not set, the type of the operation is sent. | String | |
CamelKeycloakPermissionResourceNames (common) Constant: | Comma-separated list of the resource names or IDs that evaluatePermission requests permissions for, each with the scopes of CamelKeycloakPermissionScopes when set. | String | |
CamelKeycloakPermissionScopes (common) Constant: | Comma-separated list of the scopes that evaluatePermission requests permissions for. | String | |
CamelKeycloakSubjectToken (common) Constant: | A token of the user on whose behalf evaluatePermission evaluates the permissions, sent as the subject token of the authorization request. | String | |
CamelKeycloakPermissionAudience (common) Constant: | The client ID of the resource server whose permissions evaluatePermission evaluates, sent as the audience of the authorization request. | String | |
CamelKeycloakPermissionsOnly (common) Constant: | Whether evaluatePermission returns only the granted permissions, instead of obtaining a requesting party token (RPT) that holds them. Default false. | Boolean | |
CamelKeycloakOrganizationId (common) Constant: | The organization ID. | String | |
CamelKeycloakOrganizationName (common) Constant: | The organization name. | String | |
CamelKeycloakOrganizationAlias (common) Constant: | The organization alias. | String | |
CamelKeycloakOrganizationDescription (common) Constant: | The organization description. | String | |
CamelKeycloakOrganizationRedirectUrl (common) Constant: | The organization redirect URL. | String | |
CamelKeycloakOrganizationDomain (common) Constant: | The domain name that createOrganization adds to the new organization. | String | |
CamelKeycloakOrganizationSearch (common) Constant: | The text that searchOrganizations looks for in the name and domains of the organizations. | String | |
CamelKeycloakIdentityProvider (common) Constant: | The identity provider alias for a federated identity link. | String | |
CamelKeycloakFederatedUserId (common) Constant: | The user id at the external identity provider. | String | |
CamelKeycloakFederatedUsername (common) Constant: | The username at the external identity provider. | String |
Message Body
The message body at each side of the Keycloak 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 |
| One message per event: the EventRepresentation of a user event such as a login, or the AdminEventRepresentation with eventType=admin-events. The CamelKeycloakEventType header says event or admin-event.
|
Producer input |
| Mostly not read: the operations take their input from headers, such as CamelKeycloakRealmName and CamelKeycloakUserId. With pojoRequest=true the create and update operations take the Keycloak representation, such as a UserRepresentation for createUser, or a Map or JSON text of it; a body that does not convert fails. The bulk operations take a List when the header is not set: of UserRepresentation (or a Map or JSON text of it) for bulkCreateUsers and bulkUpdateUsers, of String ids or role names for the others. introspectToken, revokeAccessToken and revokeRefreshToken take the token as text when the CamelKeycloakToken header is not set.
|
Producer output |
| Depends on the operation, which the CamelKeycloakOperation header can set with allowOperationHeader=true: get gives the Keycloak representation, such as a UserRepresentation, and list and search a List of them. Most create operations, deleteUser and some organization operations give the closed JAX-RS Response, whose status and Location header (the URL of the created resource) can be read; a status other than 2xx fails with a WebApplicationException. The others give a confirmation text such as Realm deleted successfully. The bulk operations give a Map with total, success, failed and results.
Not known when |
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.
Overview
Producer
The producer supports a comprehensive set of administrative operations on Keycloak via the Admin API, including user management, role management, client management, group management, session management, token management, identity providers, organizations, authorization services, and bulk operations.
See Keycloak Producer Operations for the full list of supported operations, configuration details, and examples.
Consumer
The consumer allows you to poll Keycloak for user events (logins, logouts, registrations) and admin events (resource creates, updates, deletes). It supports filtering by event type, operation type, date range, user, client, and IP address, with built-in fingerprint-based deduplication.
See Keycloak Consumer Operations for configuration, event processing patterns, and examples.
Security Policies
The security policy provides route-level authorization by validating Keycloak access tokens. It supports role-based and permission-based authorization, local JWT parsing and OAuth 2.0 token introspection (RFC 7662) with pluggable cache implementations.
See Keycloak Security Policies for configuration, token introspection setup, and examples.
Usage
Providing Access Tokens
The security policy expects access tokens to be provided in one of the following ways:
-
Header:
CamelKeycloakAccessToken -
Authorization Header:
Authorization: Bearer <token> -
Exchange Property:
CamelKeycloakAccessToken
// Using header
template.sendBodyAndHeader("direct:protected", "message",
"CamelKeycloakAccessToken", accessToken);
// Using Authorization header
template.sendBodyAndHeader("direct:protected", "message",
"Authorization", "Bearer " + accessToken); Route Examples
-
Java
-
YAML
from("direct:admin-only")
.policy(adminPolicy)
.transform().constant("Admin access granted")
.to("mock:admin");
from("direct:user-or-admin")
.policy(userPolicy)
.transform().constant("User access granted")
.to("mock:user");
from("rest:get:/api/documents")
.policy(documentsPolicy)
.to("direct:list-documents"); - route:
from:
uri: direct:admin-only
steps:
- policy:
ref: adminPolicy
- transform:
constant: "Admin access granted"
- to:
uri: mock:admin
- route:
from:
uri: direct:user-or-admin
steps:
- policy:
ref: userPolicy
- transform:
constant: "User access granted"
- to:
uri: mock:user
- route:
from:
uri: rest:get:/api/documents
steps:
- policy:
ref: documentsPolicy
- to:
uri: direct:list-documents Federated Identity Operations
Federated identity operations manage the links between a Keycloak user and an external identity provider account (Google, GitHub, a SAML provider, and so on). They are useful for SSO scenarios and for provisioning users with pre-linked IdP accounts during a migration.
-
addFederatedIdentity— link a user to an identity provider account. -
removeFederatedIdentity— unlink a user from an identity provider. -
getFederatedIdentities— list all identity provider links for a user.
All three require CamelKeycloakRealmName and CamelKeycloakUserId. In addition:
-
addFederatedIdentityrequiresCamelKeycloakIdentityProvider(the IdP alias) andCamelKeycloakFederatedUserId(the user id at the provider).CamelKeycloakFederatedUsernameis optional — when it is not supplied the external user id is used as the username. -
removeFederatedIdentityrequiresCamelKeycloakIdentityProvider.
getFederatedIdentities sets the out-message body to the List<FederatedIdentityRepresentation> of links.
-
Java
-
YAML
from("direct:linkAccount")
.setHeader(KeycloakConstants.REALM_NAME, constant("myrealm"))
.setHeader(KeycloakConstants.USER_ID, constant("user-uuid"))
.setHeader(KeycloakConstants.IDENTITY_PROVIDER, constant("google"))
.setHeader(KeycloakConstants.FEDERATED_USER_ID, constant("google-account-id"))
.setHeader(KeycloakConstants.FEDERATED_USERNAME, constant("jane@example.com"))
.to("keycloak:admin?operation=addFederatedIdentity");
from("direct:listLinks")
.setHeader(KeycloakConstants.REALM_NAME, constant("myrealm"))
.setHeader(KeycloakConstants.USER_ID, constant("user-uuid"))
.to("keycloak:admin?operation=getFederatedIdentities"); - route:
from:
uri: direct:linkAccount
steps:
- setHeader:
name: CamelKeycloakRealmName
constant: "myrealm"
- setHeader:
name: CamelKeycloakUserId
constant: "user-uuid"
- setHeader:
name: CamelKeycloakIdentityProvider
constant: "google"
- setHeader:
name: CamelKeycloakFederatedUserId
constant: "google-account-id"
- to:
uri: keycloak:admin?operation=addFederatedIdentity Configuration Options
| Name | Default | Description |
|---|---|---|
serverUrl | Keycloak server URL (e.g., http://localhost:8080) | |
realm | Keycloak realm name | |
clientId | Keycloak client ID | |
clientSecret | Keycloak client secret (for client credentials flow) | |
username | Username (for resource owner password flow) | |
password | Password (for resource owner password flow) | |
requiredRoles | "" | Comma-separated list of required roles (e.g., "admin,user,manager") |
requiredPermissions | "" | Comma-separated list of required permissions (e.g., "read:documents,write:documents") |
allRolesRequired | true | Whether ALL roles are required (true) or ANY role (false) |
allPermissionsRequired | true | Whether ALL permissions are required (true) or ANY permission (false) |
useResourceOwnerPasswordCredentials | false | Whether to use resource owner password flow |
Security Considerations
-
Always use HTTPS in production environments
-
Store client secrets securely (environment variables, secret management systems)
-
Regularly rotate client secrets and user passwords
-
Use the principle of least privilege when assigning roles and permissions
-
Consider token expiration and refresh strategies
Error Handling
The component throws CamelAuthorizationException when:
-
Access token is missing or invalid
-
User doesn’t have required roles
-
User doesn’t have required permissions
-
Keycloak server is unreachable
-
Token verification fails
-
Java
-
YAML
onException(CamelAuthorizationException.class)
.handled(true)
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(403))
.transform().constant("Access denied"); - onException:
exception:
- "org.apache.camel.CamelAuthorizationException"
handled:
constant:
expression: "true"
steps:
- setHeader:
name: "CamelHttpResponseCode"
constant: "403"
- transform:
constant: "Access denied" Running Integration Tests
The component includes integration tests that require a running Keycloak instance. These tests are disabled by default and only run when specific system properties are provided.
The integration tests include comprehensive testing for: * Role-based authorization with different role requirements * Permission-based authorization using custom claims and scopes * Public key verification with JWKS endpoint integration * Combined roles and permissions validation * Token parsing with and without public key verification * Different authorization header formats (Bearer token, custom header) * Token expiration and validity checks * Error handling for invalid tokens and insufficient privileges
Starting Keycloak with Docker
1. Start Keycloak Container
# Start Keycloak in development mode
docker run -p 8080:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin \
quay.io/keycloak/keycloak:latest start-dev 2. Access Keycloak Admin Console
Open your browser to http://localhost:8080/admin and login with: - Username: admin - Password: admin
Keycloak Configuration for Integration Tests
3. Create Test Realm
-
In the Keycloak Admin Console, click "Add realm"
-
Set realm name to:
test-realm -
Click "Create"
4. Create Test Client
-
In the
test-realm, go to Clients → "Create client" -
Set the following:
-
Client type:
OpenID Connect -
Client ID:
test-client -
Next → Client authentication:
ON -
Authorization:
ON(optional, for advanced features) -
Next → Valid redirect URIs:
* -
Click "Save"
-
-
Go to Credentials tab and copy the Client Secret
5. Create Test Roles
-
Go to Realm roles → "Create role"
-
Create the following roles:
-
admin-role -
user -
reader
-
6. Create Test Users
Create three test users with the following configuration:
User 1: myuser 1. Go to Users → "Add user" 2. Set: - Username: myuser - Email: myuser@test.com - First name: My - Last name: User - Click "Create" 3. Go to Credentials tab → "Set password" - Password: pippo123 - Temporary: OFF 4. Go to Role mapping tab → "Assign role" - Assign role: admin-role
User 2: test-user 1. Create user with: - Username: test-user - Password: user123 (temporary: OFF) - Assign role: user
User 3: reader-user 1. Create user with: - Username: reader-user - Password: reader123 (temporary: OFF) - Assign role: reader
Running the Integration Tests
7. Execute Tests with Maven
Run All Integration Tests:
# Run integration tests with required properties
mvn test -Dtest=KeycloakSecurityIT \
-Dkeycloak.server.url=http://localhost:8080 \
-Dkeycloak.realm=test-realm \
-Dkeycloak.client.id=test-client \
-Dkeycloak.client.secret=YOUR_CLIENT_SECRET Run Specific Test Categories:
# Test only role-based authorization
mvn test -Dtest=KeycloakSecurityIT#testKeycloakSecurityPolicyWithValidAdminToken,testKeycloakSecurityPolicyWithValidUserToken,testKeycloakSecurityPolicyUserCannotAccessAdminRoute \
-Dkeycloak.server.url=http://localhost:8080 \
-Dkeycloak.realm=test-realm \
-Dkeycloak.client.id=test-client \
-Dkeycloak.client.secret=YOUR_CLIENT_SECRET
# Test only permissions-based authorization
mvn test -Dtest=KeycloakSecurityIT#testKeycloakSecurityPolicyWithPermissions,testKeycloakSecurityPolicyWithScopeBasedPermissions,testKeycloakSecurityPolicyWithCombinedRolesAndPermissions \
-Dkeycloak.server.url=http://localhost:8080 \
-Dkeycloak.realm=test-realm \
-Dkeycloak.client.id=test-client \
-Dkeycloak.client.secret=YOUR_CLIENT_SECRET
# Test only public key verification
mvn test -Dtest=KeycloakSecurityIT#testKeycloakSecurityPolicyWithPublicKeyVerification,testParseTokenDirectlyWithPublicKey \
-Dkeycloak.server.url=http://localhost:8080 \
-Dkeycloak.realm=test-realm \
-Dkeycloak.client.id=test-client \
-Dkeycloak.client.secret=YOUR_CLIENT_SECRET Replace YOUR_CLIENT_SECRET with the actual client secret from step 4.
Run Manual Producer Tests:
The KeycloakProducerIT test contains manual integration tests for producer operations. These tests are disabled by default and require explicit activation:
# Run manual producer integration tests
mvn test -Dtest=KeycloakProducerIT \
-Dmanual.keycloak.test=true \
-Dkeycloak.server.url=http://localhost:8080 \
-Dkeycloak.realm=master \
-Dkeycloak.username=admin \
-Dkeycloak.password=admin The -Dmanual.keycloak.test=true flag is required to run KeycloakProducerIT tests. Without this flag, the tests will be skipped even if other Keycloak properties are provided. This prevents the tests from accidentally running in automated CI environments. |
8. Alternative: Set Environment Variables
# For KeycloakSecurityIT tests
export KEYCLOAK_SERVER_URL=http://localhost:8080
export KEYCLOAK_REALM=test-realm
export KEYCLOAK_CLIENT_ID=test-client
export KEYCLOAK_CLIENT_SECRET=YOUR_CLIENT_SECRET
# Run security tests
mvn test -Dtest=KeycloakSecurityIT \
-Dkeycloak.server.url=$KEYCLOAK_SERVER_URL \
-Dkeycloak.realm=$KEYCLOAK_REALM \
-Dkeycloak.client.id=$KEYCLOAK_CLIENT_ID \
-Dkeycloak.client.secret=$KEYCLOAK_CLIENT_SECRET
# For manual producer tests (KeycloakProducerIT)
export KEYCLOAK_SERVER_URL=http://localhost:8080
export KEYCLOAK_REALM=master
export KEYCLOAK_USERNAME=admin
export KEYCLOAK_PASSWORD=admin
# Run manual producer tests (requires explicit flag)
mvn test -Dtest=KeycloakProducerIT \
-Dmanual.keycloak.test=true \
-Dkeycloak.server.url=$KEYCLOAK_SERVER_URL \
-Dkeycloak.realm=$KEYCLOAK_REALM \
-Dkeycloak.username=$KEYCLOAK_USERNAME \
-Dkeycloak.password=$KEYCLOAK_PASSWORD Troubleshooting
Tests are skipped: - For KeycloakSecurityIT: Verify all four required properties are provided and Keycloak is running on the specified URL. - For KeycloakProducerIT: Ensure -Dmanual.keycloak.test=true is set along with the required Keycloak properties.
401 Unauthorized: Check that: - Users exist with correct passwords - Users have the required roles assigned - Client credentials are correct
Connection refused: Ensure Keycloak is running and accessible at the specified URL.
Token validation errors: Verify the realm name and client configuration match exactly.
Setting up Permissions in Keycloak
For permissions-based authorization, you have several options to include permissions in tokens:
Option 1: Custom Claims Mapper
-
In your realm, go to Client Scopes → roles → Mappers → Create mapper
-
Set the following:
-
Mapper Type:
User Attribute -
Name:
permissions-mapper -
User Attribute:
permissions -
Token Claim Name:
permissions -
Claim JSON Type:
JSON -
Add to ID token:
ON -
Add to access token:
ON
-
-
Add the
permissionsattribute to users:-
Go to Users → Select user → Attributes tab
-
Add attribute:
permissionswith value like["read:documents", "write:documents"]
-
Option 2: Scope-based Permissions
-
Configure client scopes:
-
Go to Client Scopes → Create client scope
-
Scope Name:
documents -
Protocol:
openid-connect
-
-
Add scope to client:
-
Go to Clients → Your client → Client Scopes tab
-
Add the scope as Default or Optional
-
-
In your application code, you can then use scopes as permissions:
KeycloakSecurityPolicy policy = new KeycloakSecurityPolicy();
policy.setRequiredPermissions("documents,users,admin");
policy.setAllPermissionsRequired(false); // ANY permission Option 3: Authorization Services (Advanced)
For complex permission models, enable Keycloak Authorization Services:
-
Go to Clients → Your client → Settings → Authorization Enabled:
ON -
Configure Resources, Scopes, and Policies in the Authorization tab
-
Enable Authorization on the client
Note: Full Authorization Services integration requires additional setup and is more complex than the simple approaches above.