This is an automated email from the ASF dual-hosted git repository.

oscerd pushed a commit to branch camel-4.18.x
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/camel-4.18.x by this push:
     new b62170072348 CAMEL-23738: camel-keycloak - always verify access token 
even without required roles/permissions (#23958) (#23981)
b62170072348 is described below

commit b62170072348cc4073ddf705ad716aa3678d6c09
Author: Andrea Cosentino <[email protected]>
AuthorDate: Fri Jun 12 11:07:29 2026 +0200

    CAMEL-23738: camel-keycloak - always verify access token even without 
required roles/permissions (#23958) (#23981)
    
    (cherry picked from commit 1477cb4e87b2c301f1cdcddca5b153fbbef6934b)
    
    Signed-off-by: Andrea Cosentino <[email protected]>
    Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
---
 .../src/main/docs/keycloak-component.adoc          |   5 +
 .../security/KeycloakSecurityProcessor.java        |  40 ++++++-
 .../security/KeycloakSecurityProcessorTest.java    | 118 +++++++++++++++++++++
 .../ROOT/pages/camel-4x-upgrade-guide-4_18.adoc    |  11 ++
 4 files changed, 172 insertions(+), 2 deletions(-)

diff --git a/components/camel-keycloak/src/main/docs/keycloak-component.adoc 
b/components/camel-keycloak/src/main/docs/keycloak-component.adoc
index d5eb6288a9e2..36f837822ab4 100644
--- a/components/camel-keycloak/src/main/docs/keycloak-component.adoc
+++ b/components/camel-keycloak/src/main/docs/keycloak-component.adoc
@@ -3416,6 +3416,11 @@ beans:
 ----
 ====
 
+NOTE: When an access token is present, it is always verified - signature, 
issuer and expiry for local JWT
+verification, or active state and issuer when token introspection is enabled - 
regardless of whether
+`requiredRoles` or `requiredPermissions` are configured. Role and permission 
checks are applied only after the
+token has been verified. A request without a token is rejected.
+
 === Role-based Authorization
 
 [tabs]
diff --git 
a/components/camel-keycloak/src/main/java/org/apache/camel/component/keycloak/security/KeycloakSecurityProcessor.java
 
b/components/camel-keycloak/src/main/java/org/apache/camel/component/keycloak/security/KeycloakSecurityProcessor.java
index 08910a810c3f..89c2608a0b49 100644
--- 
a/components/camel-keycloak/src/main/java/org/apache/camel/component/keycloak/security/KeycloakSecurityProcessor.java
+++ 
b/components/camel-keycloak/src/main/java/org/apache/camel/component/keycloak/security/KeycloakSecurityProcessor.java
@@ -58,11 +58,23 @@ public class KeycloakSecurityProcessor extends 
DelegateProcessor {
                 throw new CamelAuthorizationException("Access token not found 
in exchange", exchange);
             }
 
-            if (!policy.getRequiredRolesAsList().isEmpty()) {
+            boolean rolesRequired = !policy.getRequiredRolesAsList().isEmpty();
+            boolean permissionsRequired = 
!policy.getRequiredPermissionsAsList().isEmpty();
+
+            // The token is always authenticated before the route runs 
(signature, issuer and expiry for
+            // local JWT verification, or active state and issuer for 
introspection). validateRoles() and
+            // validatePermissions() already authenticate the token, but they 
only run when roles or
+            // permissions are required; when neither is configured, 
authenticate here so that an invalid or
+            // unverifiable token is rejected instead of accepted. 
Authorization checks run after authentication.
+            if (!rolesRequired && !permissionsRequired) {
+                authenticateToken(accessToken, exchange);
+            }
+
+            if (rolesRequired) {
                 validateRoles(accessToken, exchange);
             }
 
-            if (!policy.getRequiredPermissionsAsList().isEmpty()) {
+            if (permissionsRequired) {
                 validatePermissions(accessToken, exchange);
             }
 
@@ -76,6 +88,30 @@ public class KeycloakSecurityProcessor extends 
DelegateProcessor {
         }
     }
 
+    /**
+     * Authenticates the access token without applying any authorization (role 
or permission) checks. When token
+     * introspection is enabled the token is validated against Keycloak's 
introspection endpoint (active state and, when
+     * issuer validation is enabled, the issuer); otherwise the token 
signature, issuer and expiry are verified locally.
+     * This guarantees that an invalid or unverifiable token is rejected even 
when the policy does not require any roles
+     * or permissions.
+     */
+    private void authenticateToken(String accessToken, Exchange exchange) 
throws Exception {
+        if (policy.isUseTokenIntrospection() && policy.getTokenIntrospector() 
!= null) {
+            KeycloakTokenIntrospector.IntrospectionResult introspectionResult
+                    = KeycloakSecurityHelper.introspectToken(accessToken, 
policy.getTokenIntrospector());
+
+            if (!introspectionResult.isActive()) {
+                throw new CamelAuthorizationException("Token is not active 
(may be revoked or expired)", exchange);
+            }
+
+            if (policy.isValidateIssuer()) {
+                validateIssuerFromIntrospection(introspectionResult, exchange);
+            }
+        } else {
+            parseAndVerifyToken(accessToken, exchange);
+        }
+    }
+
     private String getAccessToken(Exchange exchange) throws Exception {
         // Get token from exchange property (application-controlled, TRUSTED)
         String propertyToken = 
exchange.getProperty(KeycloakSecurityConstants.ACCESS_TOKEN_PROPERTY, 
String.class);
diff --git 
a/components/camel-keycloak/src/test/java/org/apache/camel/component/keycloak/security/KeycloakSecurityProcessorTest.java
 
b/components/camel-keycloak/src/test/java/org/apache/camel/component/keycloak/security/KeycloakSecurityProcessorTest.java
new file mode 100644
index 000000000000..89fe43304bbb
--- /dev/null
+++ 
b/components/camel-keycloak/src/test/java/org/apache/camel/component/keycloak/security/KeycloakSecurityProcessorTest.java
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.keycloak.security;
+
+import java.security.KeyPairGenerator;
+import java.security.PublicKey;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.camel.CamelAuthorizationException;
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.component.keycloak.security.cache.TokenCache;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.support.DefaultExchange;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * Verifies that {@link KeycloakSecurityProcessor} authenticates the access 
token even when the policy does not require
+ * any roles or permissions, so an invalid or unverifiable token is rejected 
instead of being accepted.
+ */
+class KeycloakSecurityProcessorTest {
+
+    private CamelContext context;
+
+    @BeforeEach
+    void setUp() {
+        context = new DefaultCamelContext();
+        context.start();
+    }
+
+    @AfterEach
+    void tearDown() {
+        context.stop();
+    }
+
+    private Exchange bearer(String token) {
+        Exchange exchange = new DefaultExchange(context);
+        exchange.getIn().setHeader("Authorization", "Bearer " + token);
+        return exchange;
+    }
+
+    @Test
+    void testInvalidTokenRejectedWithoutRolesOrPermissionsLocalJwt() throws 
Exception {
+        // Documented "Basic Setup": no required roles, no required 
permissions.
+        KeycloakSecurityPolicy policy = new KeycloakSecurityPolicy();
+        policy.setServerUrl("http://localhost:8080";);
+        policy.setRealm("test-realm");
+        policy.setClientId("test-client");
+        policy.setClientSecret("test-secret");
+        // Configure a key so local JWT verification can run fully offline.
+        policy.setAutoFetchPublicKey(false);
+        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
+        generator.initialize(2048);
+        PublicKey publicKey = generator.generateKeyPair().getPublic();
+        policy.setPublicKey(publicKey);
+
+        AtomicBoolean routeReached = new AtomicBoolean(false);
+        KeycloakSecurityProcessor processor = new KeycloakSecurityProcessor(e 
-> routeReached.set(true), policy);
+
+        assertThrows(CamelAuthorizationException.class, () -> 
processor.process(bearer("x")));
+        assertFalse(routeReached.get(), "Route body must not be reached for an 
unverified token");
+    }
+
+    @Test
+    void testInactiveTokenRejectedWithoutRolesOrPermissionsIntrospection() 
throws Exception {
+        // An introspector that reports the token as inactive, evaluated 
offline.
+        KeycloakTokenIntrospector introspector = new KeycloakTokenIntrospector(
+                "http://localhost:8080";, "test-realm", "test-client", 
"test-secret", (TokenCache) null) {
+            @Override
+            public IntrospectionResult introspect(String token) {
+                return new IntrospectionResult(Map.<String, Object> 
of("active", false));
+            }
+        };
+
+        // Basic Setup (no roles/permissions) with introspection enabled.
+        KeycloakSecurityPolicy policy = new KeycloakSecurityPolicy() {
+            @Override
+            public boolean isUseTokenIntrospection() {
+                return true;
+            }
+
+            @Override
+            public KeycloakTokenIntrospector getTokenIntrospector() {
+                return introspector;
+            }
+        };
+        policy.setServerUrl("http://localhost:8080";);
+        policy.setRealm("test-realm");
+        policy.setClientId("test-client");
+        policy.setClientSecret("test-secret");
+
+        AtomicBoolean routeReached = new AtomicBoolean(false);
+        KeycloakSecurityProcessor processor = new KeycloakSecurityProcessor(e 
-> routeReached.set(true), policy);
+
+        assertThrows(CamelAuthorizationException.class, () -> 
processor.process(bearer("x")));
+        assertFalse(routeReached.get(), "Route body must not be reached for an 
inactive token");
+    }
+}
diff --git 
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_18.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_18.adoc
index e3f5a6ba3142..1d040ae9e08b 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_18.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_18.adoc
@@ -13,6 +13,17 @@ See the xref:camel-upgrade-recipes-tool.adoc[documentation] 
page for details.
 
 == Upgrading from 4.18.2 to 4.18.3
 
+=== camel-keycloak
+
+The `KeycloakSecurityPolicy` route policy now always verifies the access token 
when one is present - signature,
+issuer and expiry for local JWT verification, or active state and issuer when 
token introspection is enabled -
+even when neither `requiredRoles` nor `requiredPermissions` is configured. 
Previously the token was only verified
+when at least one role or permission was required.
+
+Routes that attach a `KeycloakSecurityPolicy` without any roles or permissions 
and that previously forwarded an
+unverified or invalid token will now have such requests rejected with a 
`CamelAuthorizationException`. Provide a
+valid, verifiable token (or configure `requiredRoles` / `requiredPermissions`) 
for these routes.
+
 === camel-langchain4j-tools / camel-langchain4j-agent / camel-spring-ai-tools
 
 LLM tool argument field names are now filtered against the tool's declared 
parameter schema

Reply via email to