Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Replace obsolete Keycloak adapter with Nimbus based JWT token verifier (#2650)

Rich Turner73b9d12f2dac
diff --git a/agent/build.gradle b/agent/build.gradle
index ae5623200..a8957852a 100644
--- a/agent/build.gradle
+++ b/agent/build.gradle
@@ -65,6 +65,8 @@ dependencies {
testImplementation "org.mockito:mockito-core:$mockitoVersion"
testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junitVersion"
testRuntimeOnly "org.junit.platform:junit-platform-launcher"
+
+ implementation "org.bouncycastle:bcprov-jdk18on:$bouncyCastleVersion"
}
protobuf {
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHTTPServerProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHTTPServerProtocol.java
index d7d79c03d..e6169e22d 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHTTPServerProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHTTPServerProtocol.java
@@ -98,7 +98,7 @@ public abstract class AbstractHTTPServerProtocol<T extends AbstractHTTPServerPro
null,
Stream.of(
List.of((Object)new RealmInjectorFilter(agent.getRealm())), // Need this as realm is in the context path of the deployment
- getStandardProviders(devMode, 0),
+ getStandardProviders(devMode),
getApiSingletons()).flatMap(Collection::stream).toList());
deploy(application);
diff --git a/container/build.gradle b/container/build.gradle
index e3bc70418..e5c20a604 100644
--- a/container/build.gradle
+++ b/container/build.gradle
@@ -26,11 +26,11 @@ dependencies {
api "org.jboss.resteasy:resteasy-multipart-provider:$resteasyVersion"
api "org.jboss.resteasy:resteasy-validator-provider:$resteasyVersion"
- api "org.keycloak:keycloak-client-registration-api:$keycloakVersion"
- // This is the generic keycloak adapter that isn't kept up to date - deprecated possibly?
- // They now only develop keycloak-jboss-adapter-core which is wildfly specific and would need some work to integrate
- api "org.keycloak:keycloak-adapter-core:$keycloakVersion"
- api "org.keycloak:keycloak-policy-enforcer:$keycloakVersion"
+ api "jakarta.security.enterprise:jakarta.security.enterprise-api:4.0.0"
+ api "org.glassfish.soteria:jakarta.security.enterprise:3.0.4"
+ api "com.nimbusds:nimbus-jose-jwt:10.4.2"
+
+
api "org.keycloak:keycloak-admin-client:$keycloakVersion"
api "org.postgresql:postgresql:$postgresJdbcVersion"
diff --git a/container/src/main/java/org/keycloak/adapters/spi/AdapterSessionStore.java b/container/src/main/java/org/keycloak/adapters/spi/AdapterSessionStore.java
deleted file mode 100644
index 490e90bf0..000000000
--- a/container/src/main/java/org/keycloak/adapters/spi/AdapterSessionStore.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.spi;
-
-/**
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public interface AdapterSessionStore {
- void saveRequest();
- boolean restoreRequest();
-}
diff --git a/container/src/main/java/org/keycloak/adapters/spi/AuthChallenge.java b/container/src/main/java/org/keycloak/adapters/spi/AuthChallenge.java
deleted file mode 100644
index 2920ae681..000000000
--- a/container/src/main/java/org/keycloak/adapters/spi/AuthChallenge.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.spi;
-
-/**
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public interface AuthChallenge {
- /**
- *
- * @param exchange
- * @return challenge sent
- */
- boolean challenge(HttpFacade exchange);
-
- /**
- * Some platforms need the error code that will be sent (i.e. Undertow)
- *
- * @return
- */
- int getResponseCode();
-}
diff --git a/container/src/main/java/org/keycloak/adapters/spi/AuthOutcome.java b/container/src/main/java/org/keycloak/adapters/spi/AuthOutcome.java
deleted file mode 100644
index 62d83fceb..000000000
--- a/container/src/main/java/org/keycloak/adapters/spi/AuthOutcome.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.spi;
-
-/**
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public enum AuthOutcome {
- NOT_ATTEMPTED, FAILED, AUTHENTICATED, NOT_AUTHENTICATED, LOGGED_OUT
-}
diff --git a/container/src/main/java/org/keycloak/adapters/spi/AuthenticationError.java b/container/src/main/java/org/keycloak/adapters/spi/AuthenticationError.java
deleted file mode 100644
index e95ee72ef..000000000
--- a/container/src/main/java/org/keycloak/adapters/spi/AuthenticationError.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.spi;
-
-/**
- * Common marker interface used by keycloak client adapters when there is an error. For servlets, you'll be able
- * to extract this error from the HttpServletRequest.getAttribute(AuthenticationError.class.getName()). Each protocol
- * will have their own subclass of this interface.
- *
- *
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public interface AuthenticationError {
-}
diff --git a/container/src/main/java/org/keycloak/adapters/spi/HttpFacade.java b/container/src/main/java/org/keycloak/adapters/spi/HttpFacade.java
deleted file mode 100644
index 39d5c33ec..000000000
--- a/container/src/main/java/org/keycloak/adapters/spi/HttpFacade.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.spi;
-
-import java.security.cert.X509Certificate;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.List;
-
-/**
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public interface HttpFacade {
- Request getRequest();
-
- Response getResponse();
-
- X509Certificate[] getCertificateChain();
-
- interface Request {
-
- String getMethod();
- /**
- * Full request URI with query params
- *
- * @return
- */
- String getURI();
-
- /**
- * Get the request relative path.
- *
- * @return the request relative path
- */
- String getRelativePath();
-
- /**
- * HTTPS?
- *
- * @return
- */
- boolean isSecure();
-
- /**
- * Get first query or form param
- *
- * @param param
- * @return
- */
- String getFirstParam(String param);
- String getQueryParamValue(String param);
- Cookie getCookie(String cookieName);
- String getHeader(String name);
- List<String> getHeaders(String name);
- InputStream getInputStream();
- InputStream getInputStream(boolean buffered);
-
- String getRemoteAddr();
- void setError(AuthenticationError error);
- void setError(LogoutError error);
- }
-
- interface Response {
- void setStatus(int status);
- void addHeader(String name, String value);
- void setHeader(String name, String value);
- void resetCookie(String name, String path);
- void setCookie(String name, String value, String path, String domain, int maxAge, boolean secure, boolean httpOnly);
- OutputStream getOutputStream();
- void sendError(int code);
- void sendError(int code, String message);
-
- /**
- * If the response is finished, end it.
- *
- */
- void end();
- }
-
- public class Cookie {
- protected String name;
- protected String value;
- protected int version;
- protected String domain;
- protected String path;
-
- public Cookie(String name, String value, int version, String domain, String path) {
- this.name = name;
- this.value = value;
- this.version = version;
- this.domain = domain;
- this.path = path;
- }
-
- public String getName() {
- return name;
- }
-
- public String getValue() {
- return value;
- }
-
- public int getVersion() {
- return version;
- }
-
- public String getDomain() {
- return domain;
- }
-
- public String getPath() {
- return path;
- }
- }
-}
diff --git a/container/src/main/java/org/keycloak/adapters/spi/InMemorySessionIdMapper.java b/container/src/main/java/org/keycloak/adapters/spi/InMemorySessionIdMapper.java
deleted file mode 100644
index 808d94818..000000000
--- a/container/src/main/java/org/keycloak/adapters/spi/InMemorySessionIdMapper.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.spi;
-
-import org.jboss.logging.Logger;
-
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * Maps external principal and SSO id to internal local http session id
- *
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class InMemorySessionIdMapper implements SessionIdMapper {
-
- private static final Logger LOG = Logger.getLogger(InMemorySessionIdMapper.class.getName());
-
- ConcurrentHashMap<String, String> ssoToSession = new ConcurrentHashMap<>();
- ConcurrentHashMap<String, String> sessionToSso = new ConcurrentHashMap<>();
- ConcurrentHashMap<String, Set<String>> principalToSession = new ConcurrentHashMap<>();
- ConcurrentHashMap<String, String> sessionToPrincipal = new ConcurrentHashMap<>();
-
- @Override
- public boolean hasSession(String id) {
- return sessionToSso.containsKey(id) || sessionToPrincipal.containsKey(id);
- }
-
- @Override
- public void clear() {
- ssoToSession.clear();
- sessionToSso.clear();
- principalToSession.clear();
- sessionToPrincipal.clear();
- }
-
- @Override
- public Set<String> getUserSessions(String principal) {
- Set<String> lookup = principalToSession.get(principal);
- if (lookup == null) return null;
- Set<String> copy = new HashSet<>();
- copy.addAll(lookup);
- return copy;
- }
-
- @Override
- public String getSessionFromSSO(String sso) {
- return ssoToSession.get(sso);
- }
-
- @Override
- public void map(String sso, String principal, String session) {
- LOG.debugf("Adding mapping (%s, %s, %s)", sso, principal, session);
-
- if (sso != null) {
- ssoToSession.put(sso, session);
- sessionToSso.put(session, sso);
- }
-
- if (principal == null) {
- return;
- }
-
- Set<String> userSessions = principalToSession.get(principal);
- if (userSessions == null) {
- final Set<String> tmp = Collections.synchronizedSet(new HashSet<String>());
- userSessions = principalToSession.putIfAbsent(principal, tmp);
- if (userSessions == null) {
- userSessions = tmp;
- }
- }
- userSessions.add(session);
- sessionToPrincipal.put(session, principal);
- }
-
- @Override
- public void removeSession(String session) {
- LOG.debugf("Removing session %s", session);
-
- String sso = sessionToSso.remove(session);
- if (sso != null) {
- ssoToSession.remove(sso);
- }
- String principal = sessionToPrincipal.remove(session);
- if (principal != null) {
- Set<String> sessions = principalToSession.get(principal);
- sessions.remove(session);
- if (sessions.isEmpty()) {
- principalToSession.remove(principal, sessions);
- }
- }
- }
-
-
-}
diff --git a/container/src/main/java/org/keycloak/adapters/spi/KeycloakAccount.java b/container/src/main/java/org/keycloak/adapters/spi/KeycloakAccount.java
deleted file mode 100644
index ce6863ccb..000000000
--- a/container/src/main/java/org/keycloak/adapters/spi/KeycloakAccount.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.spi;
-
-import java.security.Principal;
-import java.util.Set;
-
-/**
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public interface KeycloakAccount {
- Principal getPrincipal();
-
- Set<String> getRoles();
-}
diff --git a/container/src/main/java/org/keycloak/adapters/spi/LogoutError.java b/container/src/main/java/org/keycloak/adapters/spi/LogoutError.java
deleted file mode 100644
index 091bf8b31..000000000
--- a/container/src/main/java/org/keycloak/adapters/spi/LogoutError.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.spi;
-
-/**
- * Common marker interface used by keycloak client adapters when there is an error. For servlets, you'll be able
- * to extract this error from the HttpServletRequest.getAttribute(LogoutError.class.getName()). Each protocol
- * will have their own subclass of this interface.
- *
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public interface LogoutError {
-}
diff --git a/container/src/main/java/org/keycloak/adapters/spi/SessionIdMapper.java b/container/src/main/java/org/keycloak/adapters/spi/SessionIdMapper.java
deleted file mode 100644
index b50e37b79..000000000
--- a/container/src/main/java/org/keycloak/adapters/spi/SessionIdMapper.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.spi;
-
-import java.util.Set;
-
-/**
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public interface SessionIdMapper {
- /**
- * Returns {@code true} if the mapper contains mapping for the given HTTP session ID.
- * @param id
- * @return
- */
- boolean hasSession(String id);
-
- /**
- * Clears all mappings from this mapper.
- */
- void clear();
-
- /**
- * Returns set of HTTP session IDs for the given principal.
- * @param principal Principal
- * @return
- */
- Set<String> getUserSessions(String principal);
-
- /**
- * Returns HTTP session ID from the given user session ID.
- * @param sso User session ID
- * @return
- */
- String getSessionFromSSO(String sso);
-
- /**
- * Establishes mapping between user session ID, principal and HTTP session ID.
- * @param sso User session ID
- * @param principal Principal
- * @param session HTTP session ID
- */
- void map(String sso, String principal, String session);
-
- /**
- * Removes mappings for the given HTTP session ID.
- * @param session HTTP session ID.
- */
- void removeSession(String session);
-}
diff --git a/container/src/main/java/org/keycloak/adapters/spi/SessionIdMapperUpdater.java b/container/src/main/java/org/keycloak/adapters/spi/SessionIdMapperUpdater.java
deleted file mode 100644
index 637156ccf..000000000
--- a/container/src/main/java/org/keycloak/adapters/spi/SessionIdMapperUpdater.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright 2017 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.spi;
-
-/**
- * Classes implementing this interface represent a mechanism for updating {@link SessionIdMapper} entries.
- * @author hmlnarik
- */
-public interface SessionIdMapperUpdater {
- /**
- * {@link SessionIdMapper} entries are updated directly.
- */
- public static final SessionIdMapperUpdater DIRECT = new SessionIdMapperUpdater() {
- @Override public void clear(SessionIdMapper idMapper) {
- idMapper.clear();
- }
-
- @Override public void map(SessionIdMapper idMapper, String sso, String principal, String httpSessionId) {
- idMapper.map(sso, principal, httpSessionId);
- }
-
- @Override public void removeSession(SessionIdMapper idMapper, String httpSessionId) {
- idMapper.removeSession(httpSessionId);
- }
-
- @Override public boolean refreshMapping(SessionIdMapper idMapper, String httpSessionId) {
- return false;
- }
- };
-
- /**
- * Only HTTP session is manipulated with, {@link SessionIdMapper} entries are not updated by this updater and
- * they have to be updated by some other means, e.g. by some listener of HTTP session changes.
- */
- public static final SessionIdMapperUpdater EXTERNAL = new SessionIdMapperUpdater() {
- @Override public void clear(SessionIdMapper idMapper) { }
-
- @Override public void map(SessionIdMapper idMapper, String sso, String principal, String httpSessionId) { }
-
- @Override public void removeSession(SessionIdMapper idMapper, String httpSessionId) { }
-
- @Override public boolean refreshMapping(SessionIdMapper idMapper, String httpSessionId) { return false; }
- };
-
- /**
- * Delegates to {@link SessionIdMapper#clear} method..
- */
- void clear(SessionIdMapper idMapper);
-
- /**
- * Delegates to {@link SessionIdMapper#map} method.
- * @param idMapper Mapper
- * @param sso User session ID
- * @param principal Principal
- * @param session HTTP session ID
- */
- void map(SessionIdMapper idMapper, String sso, String principal, String session);
-
- /**
- * Delegates to {@link SessionIdMapper#removeSession} method.
- * @param idMapper Mapper
- * @param session HTTP session ID.
- */
- void removeSession(SessionIdMapper idMapper, String session);
-
- /**
- * Refreshes the mapping in the {@code idMapper} from the internal source of this mapped updater
- * and maps it via {@link SessionIdMapper#map} method.
- * @param idMapper Mapper
- * @param httpSessionId HTTP session ID.
- * @return {@code true} if the mapping existed in the internal source of this mapped updater
- * and has been refreshed, {@code false} otherwise
- */
- boolean refreshMapping(SessionIdMapper idMapper, String httpSessionId);
-}
diff --git a/container/src/main/java/org/keycloak/adapters/spi/UserSessionManagement.java b/container/src/main/java/org/keycloak/adapters/spi/UserSessionManagement.java
deleted file mode 100644
index 5808b0b69..000000000
--- a/container/src/main/java/org/keycloak/adapters/spi/UserSessionManagement.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.spi;
-
-import java.util.List;
-
-/**
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public interface UserSessionManagement {
-
- void logoutAll();
-
- void logoutHttpSessions(List<String> ids);
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/AbstractUndertowKeycloakAuthMech.java b/container/src/main/java/org/keycloak/adapters/undertow/AbstractUndertowKeycloakAuthMech.java
deleted file mode 100644
index 835d043fb..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/AbstractUndertowKeycloakAuthMech.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.security.api.AuthenticationMechanism;
-import io.undertow.security.api.NotificationReceiver;
-import io.undertow.security.api.SecurityContext;
-import io.undertow.security.api.SecurityNotification;
-import io.undertow.server.HttpServerExchange;
-import io.undertow.util.AttachmentKey;
-import io.undertow.util.Headers;
-import io.undertow.util.StatusCodes;
-import org.keycloak.KeycloakSecurityContext;
-import org.keycloak.adapters.*;
-import org.keycloak.adapters.spi.AuthChallenge;
-import org.keycloak.adapters.spi.AuthOutcome;
-import org.keycloak.adapters.spi.HttpFacade;
-import org.keycloak.enums.TokenStore;
-
-/**
- * Abstract base class for a Keycloak-enabled Undertow AuthenticationMechanism.
- *
- * @author Stan Silvert [email protected] (C) 2014 Red Hat Inc.
- */
-public abstract class AbstractUndertowKeycloakAuthMech implements AuthenticationMechanism {
- public static final AttachmentKey<AuthChallenge> KEYCLOAK_CHALLENGE_ATTACHMENT_KEY = AttachmentKey.create(AuthChallenge.class);
- protected AdapterDeploymentContext deploymentContext;
- protected UndertowUserSessionManagement sessionManagement;
- protected String errorPage;
-
- public AbstractUndertowKeycloakAuthMech(AdapterDeploymentContext deploymentContext, UndertowUserSessionManagement sessionManagement, String errorPage) {
- this.deploymentContext = deploymentContext;
- this.sessionManagement = sessionManagement;
- this.errorPage = errorPage;
- }
-
- @Override
- public ChallengeResult sendChallenge(HttpServerExchange exchange, SecurityContext securityContext) {
- AuthChallenge challenge = exchange.getAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY);
- if (challenge != null) {
- UndertowHttpFacade facade = createFacade(exchange);
- if (challenge.challenge(facade)) {
- return new ChallengeResult(true, exchange.getStatusCode());
- }
- }
- return new ChallengeResult(false);
- }
-
- public UndertowHttpFacade createFacade(HttpServerExchange exchange) {
- return new OIDCUndertowHttpFacade(exchange);
- }
-
- protected Integer servePage(final HttpServerExchange exchange, final String location) {
- sendRedirect(exchange, location);
- return StatusCodes.TEMPORARY_REDIRECT;
- }
-
- static void sendRedirect(final HttpServerExchange exchange, final String location) {
- // TODO - String concatenation to construct URLS is extremely error prone - switch to a URI which will better handle this.
- String loc = exchange.getRequestScheme() + "://" + exchange.getHostAndPort() + location;
- exchange.getResponseHeaders().put(Headers.LOCATION, loc);
- }
-
-
-
- protected void registerNotifications(final SecurityContext securityContext) {
-
- final NotificationReceiver logoutReceiver = new NotificationReceiver() {
- @Override
- public void handleNotification(SecurityNotification notification) {
- if (notification.getEventType() != SecurityNotification.EventType.LOGGED_OUT) return;
-
- HttpServerExchange exchange = notification.getExchange();
- UndertowHttpFacade facade = createFacade(exchange);
- KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);
- KeycloakSecurityContext ksc = exchange.getAttachment(OIDCUndertowHttpFacade.KEYCLOAK_SECURITY_CONTEXT_KEY);
- if (!deployment.isBearerOnly() && ksc != null && ksc instanceof RefreshableKeycloakSecurityContext) {
- ((RefreshableKeycloakSecurityContext) ksc).logout(deployment);
- }
- AdapterTokenStore tokenStore = getTokenStore(exchange, facade, deployment, securityContext);
- tokenStore.logout();
- }
- };
-
- securityContext.registerNotificationReceiver(logoutReceiver);
- }
-
- /**
- * Call this inside your authenticate method.
- */
- protected AuthenticationMechanismOutcome keycloakAuthenticate(HttpServerExchange exchange, SecurityContext securityContext, RequestAuthenticator authenticator) {
- AuthOutcome outcome = authenticator.authenticate();
- if (outcome == AuthOutcome.AUTHENTICATED) {
- registerNotifications(securityContext);
- return AuthenticationMechanismOutcome.AUTHENTICATED;
- }
- AuthChallenge challenge = authenticator.getChallenge();
- if (challenge != null) {
- exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, challenge);
- }
-
- if (outcome == AuthOutcome.FAILED) {
- return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
- }
- return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
- }
-
- protected AdapterTokenStore getTokenStore(HttpServerExchange exchange, HttpFacade facade, KeycloakDeployment deployment, SecurityContext securityContext) {
- if (deployment.getTokenStore() == TokenStore.SESSION) {
- return new UndertowSessionTokenStore(exchange, deployment, sessionManagement, securityContext);
- } else {
- return new UndertowCookieTokenStore(facade, deployment, securityContext);
- }
- }
-
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/AbstractUndertowRequestAuthenticator.java b/container/src/main/java/org/keycloak/adapters/undertow/AbstractUndertowRequestAuthenticator.java
deleted file mode 100644
index 4ddf79070..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/AbstractUndertowRequestAuthenticator.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.security.api.SecurityContext;
-import io.undertow.server.HttpServerExchange;
-import io.undertow.server.session.Session;
-import io.undertow.util.Sessions;
-import org.keycloak.KeycloakPrincipal;
-import org.keycloak.adapters.*;
-import org.keycloak.adapters.spi.HttpFacade;
-
-/**
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @author Stan Silvert [email protected] (C) 2014 Red Hat Inc.
- * @version $Revision: 1 $
- */
-public abstract class AbstractUndertowRequestAuthenticator extends RequestAuthenticator {
- protected SecurityContext securityContext;
- protected HttpServerExchange exchange;
-
-
- public AbstractUndertowRequestAuthenticator(HttpFacade facade, KeycloakDeployment deployment, int sslRedirectPort,
- SecurityContext securityContext, HttpServerExchange exchange,
- AdapterTokenStore tokenStore) {
- super(facade, deployment, tokenStore, sslRedirectPort);
- this.securityContext = securityContext;
- this.exchange = exchange;
- }
-
- protected void propagateKeycloakContext(KeycloakUndertowAccount account) {
- exchange.putAttachment(OIDCUndertowHttpFacade.KEYCLOAK_SECURITY_CONTEXT_KEY, account.getKeycloakSecurityContext());
- }
-
- @Override
- protected OAuthRequestAuthenticator createOAuthAuthenticator() {
- return new OAuthRequestAuthenticator(this, facade, deployment, sslRedirectPort, tokenStore);
- }
-
- @Override
- protected void completeOAuthAuthentication(KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal) {
- KeycloakUndertowAccount account = createAccount(principal);
- securityContext.authenticationComplete(account, "KEYCLOAK", false);
- propagateKeycloakContext(account);
- tokenStore.saveAccountInfo(account);
- }
-
- @Override
- protected void completeBearerAuthentication(KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal, String method) {
- KeycloakUndertowAccount account = createAccount(principal);
- securityContext.authenticationComplete(account, method, false);
- propagateKeycloakContext(account);
- }
-
- @Override
- protected String changeHttpSessionId(boolean create) {
- if (create) {
- Session session = Sessions.getOrCreateSession(exchange);
- return session.getId();
- } else {
- Session session = Sessions.getSession(exchange);
- return session != null ? session.getId() : null;
- }
- }
-
- /**
- * Subclasses need to be able to create their own version of the KeycloakUndertowAccount
- * @return The account
- */
- protected abstract KeycloakUndertowAccount createAccount(KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal);
-
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/ChangeSessionId.java b/container/src/main/java/org/keycloak/adapters/undertow/ChangeSessionId.java
deleted file mode 100644
index c222d3ccb..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/ChangeSessionId.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.server.HttpServerExchange;
-import io.undertow.server.session.Session;
-import io.undertow.servlet.api.DeploymentInfo;
-import io.undertow.servlet.handlers.ServletRequestContext;
-import io.undertow.servlet.spec.HttpSessionImpl;
-import io.undertow.servlet.spec.ServletContextImpl;
-
-import java.lang.reflect.Method;
-import java.security.AccessController;
-
-/**
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class ChangeSessionId {
- /**
- * This is a hack to be backward compatible between Undertow 1.3+ and versions lower. In Undertow 1.3, a new
- * switch was added setChangeSessionIdOnLogin, this screws up session management for keycloak as after the session id
- * is uploaded to Keycloak, undertow changes the session id and it can't be invalidated.
- *
- * @param deploymentInfo
- */
- public static void turnOffChangeSessionIdOnLogin(DeploymentInfo deploymentInfo) {
- try {
- Method method = DeploymentInfo.class.getMethod("setChangeSessionIdOnLogin", boolean.class);
- method.invoke(deploymentInfo, false);
- } catch (Exception ignore) {
-
- }
- }
-
- @SuppressWarnings("removal")
- public static String changeSessionId(HttpServerExchange exchange, boolean create) {
- final ServletRequestContext sc = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
- ServletContextImpl currentServletContext = sc.getCurrentServletContext();
- HttpSessionImpl session = currentServletContext.getSession(exchange, create);
- if (session == null) {
- return null;
- }
- Session underlyingSession;
- if(System.getSecurityManager() == null) {
- underlyingSession = session.getSession();
- } else {
- underlyingSession = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
- }
-
-
- return underlyingSession.changeSessionId(exchange, currentServletContext.getSessionConfig());
- }
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/KeycloakChallenge.java b/container/src/main/java/org/keycloak/adapters/undertow/KeycloakChallenge.java
deleted file mode 100644
index 2a22d49ef..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/KeycloakChallenge.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.security.api.AuthenticationMechanism;
-import io.undertow.security.api.SecurityContext;
-import io.undertow.server.HttpServerExchange;
-
-/**
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public interface KeycloakChallenge {
- public AuthenticationMechanism.ChallengeResult sendChallenge(HttpServerExchange httpServerExchange, SecurityContext securityContext);
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/KeycloakServletExtension.java b/container/src/main/java/org/keycloak/adapters/undertow/KeycloakServletExtension.java
deleted file mode 100644
index ba36b1a68..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/KeycloakServletExtension.java
+++ /dev/null
@@ -1,217 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.security.api.AuthenticationMechanism;
-import io.undertow.security.api.AuthenticationMechanismFactory;
-import io.undertow.security.idm.Account;
-import io.undertow.security.idm.Credential;
-import io.undertow.security.idm.IdentityManager;
-import io.undertow.server.handlers.form.FormParserFactory;
-import io.undertow.servlet.ServletExtension;
-import io.undertow.servlet.api.*;
-import io.undertow.servlet.util.ImmediateInstanceHandle;
-import org.jboss.logging.Logger;
-import org.keycloak.adapters.*;
-import org.keycloak.constants.AdapterConstants;
-
-import jakarta.servlet.ServletContext;
-import java.io.ByteArrayInputStream;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.InputStream;
-import java.util.Map;
-
-/**
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class KeycloakServletExtension implements ServletExtension {
-
- protected static Logger log = Logger.getLogger(KeycloakServletExtension.class);
- private final AdapterDeploymentContext deploymentContext;
-
- public KeycloakServletExtension() {
- this(null);
- }
-
- public KeycloakServletExtension(AdapterDeploymentContext deploymentContext) {
- this.deploymentContext = deploymentContext;
- }
-
- // todo when this DeploymentInfo method of the same name is fixed.
- public boolean isAuthenticationMechanismPresent(DeploymentInfo deploymentInfo, final String mechanismName) {
- LoginConfig loginConfig = deploymentInfo.getLoginConfig();
- if (loginConfig != null) {
- for (AuthMethodConfig method : loginConfig.getAuthMethods()) {
- if (method.getName().equalsIgnoreCase(mechanismName)) {
- return true;
- }
- }
- }
- return false;
- }
-
- private static InputStream getJSONFromServletContext(ServletContext servletContext) {
- String json = servletContext.getInitParameter(AdapterConstants.AUTH_DATA_PARAM_NAME);
- if (json == null) {
- return null;
- }
- return new ByteArrayInputStream(json.getBytes());
- }
-
- private static InputStream getConfigInputStream(ServletContext context) {
- InputStream is = getJSONFromServletContext(context);
- if (is == null) {
- String path = context.getInitParameter("keycloak.config.file");
- if (path == null) {
- log.debug("using /WEB-INF/keycloak.json");
- is = context.getResourceAsStream("/WEB-INF/keycloak.json");
- } else {
- try {
- is = new FileInputStream(path);
- } catch (FileNotFoundException e) {
- throw new RuntimeException(e);
- }
- }
- }
- return is;
- }
-
-
- @Override
- @SuppressWarnings("UseSpecificCatch")
- public void handleDeployment(DeploymentInfo deploymentInfo, ServletContext servletContext) {
- if (!isAuthenticationMechanismPresent(deploymentInfo, "KEYCLOAK") && deploymentContext == null) {
- log.debug("auth-method is not keycloak!");
- return;
- }
- log.debug("KeycloakServletException initialization");
-
- // Possible scenarios:
- // 1) The deployment has a keycloak.config.resolver specified and it exists:
- // Outcome: adapter uses the resolver
- // 2) The deployment has a keycloak.config.resolver and isn't valid (doesn't exist, isn't a resolver, ...) :
- // Outcome: adapter is left unconfigured
- // 3) The deployment doesn't have a keycloak.config.resolver , but has a keycloak.json (or equivalent)
- // Outcome: adapter uses it
- // 4) The deployment doesn't have a keycloak.config.resolver nor keycloak.json (or equivalent)
- // Outcome: adapter is left unconfigured
- AdapterDeploymentContext deploymentContext = this.deploymentContext;
-
- if (deploymentContext == null) {
- KeycloakConfigResolver configResolver;
- String configResolverClass = servletContext.getInitParameter("keycloak.config.resolver");
- if (configResolverClass != null) {
- try {
- configResolver = (KeycloakConfigResolver) deploymentInfo.getClassLoader().loadClass(configResolverClass).getDeclaredConstructors()[0].newInstance();
- deploymentContext = new AdapterDeploymentContext(configResolver);
- log.info("Using " + configResolverClass + " to resolve Keycloak configuration on a per-request basis.");
- } catch (Exception ex) {
- log.warn("The specified resolver " + configResolverClass + " could NOT be loaded. Keycloak is unconfigured and will deny all requests. Reason: " + ex.getMessage());
- deploymentContext = new AdapterDeploymentContext(new KeycloakDeployment());
- }
- } else {
- InputStream is = getConfigInputStream(servletContext);
- final KeycloakDeployment deployment;
- if (is == null) {
- log.warn("No adapter configuration. Keycloak is unconfigured and will deny all requests.");
- deployment = new KeycloakDeployment();
- } else {
- deployment = KeycloakDeploymentBuilder.build(is);
- }
- deploymentContext = new AdapterDeploymentContext(deployment);
- log.debug("Keycloak is using a per-deployment configuration.");
- }
- } else {
- deploymentContext = this.deploymentContext;
- }
-
- servletContext.setAttribute(AdapterDeploymentContext.class.getName(), deploymentContext);
- UndertowUserSessionManagement userSessionManagement = new UndertowUserSessionManagement();
- final NodesRegistrationManagement nodesRegistrationManagement = new NodesRegistrationManagement();
- final ServletKeycloakAuthMech mech = createAuthenticationMechanism(deploymentInfo, deploymentContext, userSessionManagement, nodesRegistrationManagement);
-
- UndertowAuthenticatedActionsHandler.Wrapper actions = new UndertowAuthenticatedActionsHandler.Wrapper(deploymentContext);
-
- // setup handlers
-
- deploymentInfo.addOuterHandlerChainWrapper(new ServletPreAuthActionsHandler.Wrapper(deploymentContext, userSessionManagement));
- deploymentInfo.addAuthenticationMechanism("KEYCLOAK", new AuthenticationMechanismFactory() {
- @SuppressWarnings("deprecation")
- @Override
- public AuthenticationMechanism create(String s, FormParserFactory formParserFactory, Map<String, String> stringStringMap) {
- return mech;
- }
- }); // authentication
- deploymentInfo.addInnerHandlerChainWrapper(actions); // handles authenticated actions and cors.
-
- deploymentInfo.setIdentityManager(new IdentityManager() {
- @Override
- public Account verify(Account account) {
- return account;
- }
-
- @Override
- public Account verify(String id, Credential credential) {
- throw new IllegalStateException("Should never be called in Keycloak flow");
- }
-
- @Override
- public Account verify(Credential credential) {
- throw new IllegalStateException("Should never be called in Keycloak flow");
- }
- });
-
- ServletSessionConfig cookieConfig = deploymentInfo.getServletSessionConfig();
- if (cookieConfig == null) {
- cookieConfig = new ServletSessionConfig();
- }
- if (cookieConfig.getPath() == null) {
- log.debug("Setting jsession cookie path to: " + deploymentInfo.getContextPath());
- cookieConfig.setPath(deploymentInfo.getContextPath());
- deploymentInfo.setServletSessionConfig(cookieConfig);
- }
- ChangeSessionId.turnOffChangeSessionIdOnLogin(deploymentInfo);
- deploymentInfo.addListener(new ListenerInfo(UndertowNodesRegistrationManagementWrapper.class, new InstanceFactory<UndertowNodesRegistrationManagementWrapper>() {
-
- @Override
- public InstanceHandle<UndertowNodesRegistrationManagementWrapper> createInstance() throws InstantiationException {
- UndertowNodesRegistrationManagementWrapper listener = new UndertowNodesRegistrationManagementWrapper(nodesRegistrationManagement);
- return new ImmediateInstanceHandle<UndertowNodesRegistrationManagementWrapper>(listener);
- }
-
- }));
- }
-
- protected ServletKeycloakAuthMech createAuthenticationMechanism(DeploymentInfo deploymentInfo, AdapterDeploymentContext deploymentContext, UndertowUserSessionManagement userSessionManagement,
- NodesRegistrationManagement nodesRegistrationManagement) {
- log.debug("creating ServletKeycloakAuthMech");
- String errorPage = getErrorPage(deploymentInfo);
- return new ServletKeycloakAuthMech(deploymentContext, userSessionManagement, nodesRegistrationManagement, deploymentInfo.getConfidentialPortManager(), errorPage);
- }
-
- protected String getErrorPage(DeploymentInfo deploymentInfo) {
- LoginConfig loginConfig = deploymentInfo.getLoginConfig();
- String errorPage = null;
- if (loginConfig != null) {
- errorPage = loginConfig.getErrorPage();
- }
- return errorPage;
- }
-
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/KeycloakUndertowAccount.java b/container/src/main/java/org/keycloak/adapters/undertow/KeycloakUndertowAccount.java
deleted file mode 100644
index 15facef9f..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/KeycloakUndertowAccount.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.security.idm.Account;
-import org.jboss.logging.Logger;
-import org.keycloak.KeycloakPrincipal;
-import org.keycloak.adapters.*;
-
-import java.io.Serializable;
-import java.security.Principal;
-import java.util.Set;
-
-/**
-* @author <a href="mailto:[email protected]">Bill Burke</a>
-* @version $Revision: 1 $
-*/
-public class KeycloakUndertowAccount implements Account, Serializable, OidcKeycloakAccount {
- protected static Logger log = Logger.getLogger(KeycloakUndertowAccount.class);
- protected KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal;
- protected Set<String> accountRoles;
-
- public KeycloakUndertowAccount(KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal) {
- this.principal = principal;
- setRoles(principal.getKeycloakSecurityContext());
- }
-
- protected void setRoles(RefreshableKeycloakSecurityContext session) {
- Set<String> roles = AdapterUtils.getRolesFromSecurityContext(session);
- this.accountRoles = roles;
- }
-
- @Override
- public Principal getPrincipal() {
- return principal;
- }
-
- @Override
- public Set<String> getRoles() {
- return accountRoles;
- }
-
- @Override
- public RefreshableKeycloakSecurityContext getKeycloakSecurityContext() {
- return principal.getKeycloakSecurityContext();
- }
-
- public void setCurrentRequestInfo(KeycloakDeployment deployment, AdapterTokenStore tokenStore) {
- principal.getKeycloakSecurityContext().setCurrentRequestInfo(deployment, tokenStore);
- }
-
- // Check if accessToken is active and try to refresh if it's not
- public boolean checkActive() {
- // this object may have been serialized, so we need to reset realm config/metadata
- RefreshableKeycloakSecurityContext session = getKeycloakSecurityContext();
- if (session.isActive() && !session.getDeployment().isAlwaysRefreshToken()) {
- log.debug("session is active");
- return true;
- }
-
- log.debug("session is not active or refresh is enforced. Try refresh");
- boolean success = session.refreshExpiredToken(false);
- if (!success || !session.isActive()) {
- log.debug("session is not active return with failure");
-
- return false;
- }
- log.debug("refresh succeeded");
-
- setRoles(session);
- return true;
- }
-
- @Override
- public boolean equals(Object other) {
- if (this == other)
- return true;
-
- if (!(other instanceof KeycloakUndertowAccount))
- return false;
-
- KeycloakUndertowAccount otherAccount = (KeycloakUndertowAccount) other;
-
- return (this.principal != null ? this.principal.equals(otherAccount.principal) : otherAccount.principal == null) &&
- (this.accountRoles != null ? this.accountRoles.equals(otherAccount.accountRoles) : otherAccount.accountRoles == null);
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + (this.principal == null ? 0 : this.principal.hashCode());
- result = prime * result + (this.accountRoles == null ? 0 : this.accountRoles.hashCode());
- return result;
- }
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/OIDCServletUndertowHttpFacade.java b/container/src/main/java/org/keycloak/adapters/undertow/OIDCServletUndertowHttpFacade.java
deleted file mode 100644
index 295c44dc9..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/OIDCServletUndertowHttpFacade.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.server.HttpServerExchange;
-import org.keycloak.KeycloakSecurityContext;
-import org.keycloak.adapters.OIDCHttpFacade;
-import org.keycloak.adapters.undertow.ServletHttpFacade;
-
-import static org.keycloak.adapters.undertow.OIDCUndertowHttpFacade.KEYCLOAK_SECURITY_CONTEXT_KEY;
-
-/**
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class OIDCServletUndertowHttpFacade extends ServletHttpFacade implements OIDCHttpFacade {
-
- public OIDCServletUndertowHttpFacade(HttpServerExchange exchange) {
- super(exchange);
- }
-
- @Override
- public KeycloakSecurityContext getSecurityContext() {
- return exchange.getAttachment(KEYCLOAK_SECURITY_CONTEXT_KEY);
- }
-
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/OIDCUndertowHttpFacade.java b/container/src/main/java/org/keycloak/adapters/undertow/OIDCUndertowHttpFacade.java
deleted file mode 100644
index 9505f4aae..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/OIDCUndertowHttpFacade.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.server.HttpServerExchange;
-import io.undertow.util.AttachmentKey;
-import org.keycloak.KeycloakSecurityContext;
-import org.keycloak.adapters.OIDCHttpFacade;
-import org.keycloak.adapters.undertow.UndertowHttpFacade;
-
-/**
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class OIDCUndertowHttpFacade extends UndertowHttpFacade implements OIDCHttpFacade {
- public static final AttachmentKey<KeycloakSecurityContext> KEYCLOAK_SECURITY_CONTEXT_KEY = AttachmentKey.create(KeycloakSecurityContext.class);
-
- public OIDCUndertowHttpFacade(HttpServerExchange exchange) {
- super(exchange);
- }
-
- @Override
- public KeycloakSecurityContext getSecurityContext() {
- return exchange.getAttachment(KEYCLOAK_SECURITY_CONTEXT_KEY);
- }
-
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/SavedRequest.java b/container/src/main/java/org/keycloak/adapters/undertow/SavedRequest.java
deleted file mode 100644
index a0ce9ece3..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/SavedRequest.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.server.HttpServerExchange;
-import io.undertow.server.session.Session;
-import io.undertow.servlet.handlers.ServletRequestContext;
-import io.undertow.servlet.spec.HttpSessionImpl;
-
-import jakarta.servlet.http.HttpSession;
-import java.io.Serializable;
-
-/**
- * Saved servlet request.
- *
- * Note bill burke: I had to fork this because Undertow was automatically restoring the request before the code could be
- * processed and redirected.
- *
- * CachedAuthenticatedSessionHandler was restoring the request before the authentication manager could read the code from the URI
- * Originally, I copied SavedRequest as is, but there are type mismatches between Undertow 1.1.1 and 1.3.10.
- * So, trySaveRequest calls the same undertow version, removes the saved request, stores it in a different session attribute,
- * then restores the old attribute later
- *
- *
- * @author Stuart Douglas
- */
-public class SavedRequest implements Serializable {
-
- private static final String SESSION_KEY = SavedRequest.class.getName();
-
- @SuppressWarnings("removal")
- public static void trySaveRequest(final HttpServerExchange exchange) {
- io.undertow.servlet.util.SavedRequest.trySaveRequest(exchange);
- final ServletRequestContext sc = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
- HttpSessionImpl session = sc.getCurrentServletContext().getSession(exchange, true);
- Session underlyingSession;
- if(System.getSecurityManager() == null) {
- underlyingSession = session.getSession();
- } else {
- underlyingSession = java.security.AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
- }
- io.undertow.servlet.util.SavedRequest request = (io.undertow.servlet.util.SavedRequest) underlyingSession.removeAttribute(io.undertow.servlet.util.SavedRequest.class.getName());
- if (request != null) underlyingSession.setAttribute(SESSION_KEY, request);
-
-
- }
-
- @SuppressWarnings("removal")
- public static void tryRestoreRequest(final HttpServerExchange exchange, HttpSession session) {
- if(session instanceof HttpSessionImpl) {
-
- Session underlyingSession;
- if(System.getSecurityManager() == null) {
- underlyingSession = ((HttpSessionImpl) session).getSession();
- } else {
- underlyingSession = java.security.AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
- }
- io.undertow.servlet.util.SavedRequest request = (io.undertow.servlet.util.SavedRequest) underlyingSession.removeAttribute(SESSION_KEY);
- if (request != null) {
- underlyingSession.setAttribute(io.undertow.servlet.util.SavedRequest.class.getName(), request);
- io.undertow.servlet.util.SavedRequest.tryRestoreRequest(exchange, session);
-
- }
-
- }
- }
-
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/ServletHttpFacade.java b/container/src/main/java/org/keycloak/adapters/undertow/ServletHttpFacade.java
deleted file mode 100644
index c89f7e9e5..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/ServletHttpFacade.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.server.HttpServerExchange;
-import io.undertow.servlet.handlers.ServletRequestContext;
-import org.keycloak.adapters.spi.AuthenticationError;
-import org.keycloak.adapters.spi.LogoutError;
-
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletResponse;
-
-/**
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class ServletHttpFacade extends UndertowHttpFacade {
- protected HttpServletRequest request;
- protected HttpServletResponse response;
-
- public ServletHttpFacade(HttpServerExchange exchange) {
- super(exchange);
- final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
- request = (HttpServletRequest)servletRequestContext.getServletRequest();
- response = (HttpServletResponse)servletRequestContext.getServletResponse();
- }
-
- protected class RequestFacade extends UndertowHttpFacade.RequestFacade {
- @Override
- public String getFirstParam(String param) {
- return request.getParameter(param);
- }
-
- @Override
- public void setError(AuthenticationError error) {
- request.setAttribute(AuthenticationError.class.getName(), error);
-
- }
-
- @Override
- public void setError(LogoutError error) {
- request.setAttribute(LogoutError.class.getName(), error);
- }
-
-
- }
-
- protected class ResponseFacade extends UndertowHttpFacade.ResponseFacade {
- // can't call sendError from a challenge. Undertow ends up calling send error.
- /*
- @Override
- public void sendError(int code) {
- try {
- response.sendError(code);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public void sendError(int code, String message) {
- try {
- response.sendError(code, message);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- */
-
- }
-
- @Override
- public Response getResponse() {
- return new ResponseFacade();
- }
-
- @Override
- public Request getRequest() {
- return new RequestFacade();
- }
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/ServletKeycloakAuthMech.java b/container/src/main/java/org/keycloak/adapters/undertow/ServletKeycloakAuthMech.java
deleted file mode 100644
index 6e3d4f30c..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/ServletKeycloakAuthMech.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.security.api.SecurityContext;
-import io.undertow.server.HttpServerExchange;
-import io.undertow.servlet.api.ConfidentialPortManager;
-import io.undertow.servlet.handlers.ServletRequestContext;
-import io.undertow.util.Headers;
-import org.jboss.logging.Logger;
-import org.keycloak.adapters.*;
-import org.keycloak.adapters.spi.HttpFacade;
-import org.keycloak.enums.TokenStore;
-
-import jakarta.servlet.RequestDispatcher;
-import jakarta.servlet.ServletException;
-import jakarta.servlet.ServletRequest;
-import jakarta.servlet.ServletResponse;
-import java.io.IOException;
-
-/**
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @author Stan Silvert [email protected] (C) 2014 Red Hat Inc.
- * @version $Revision: 1 $
- */
-public class ServletKeycloakAuthMech extends AbstractUndertowKeycloakAuthMech {
- private static final Logger log = Logger.getLogger(ServletKeycloakAuthMech.class);
-
- protected NodesRegistrationManagement nodesRegistrationManagement;
- protected ConfidentialPortManager portManager;
-
- public ServletKeycloakAuthMech(AdapterDeploymentContext deploymentContext, UndertowUserSessionManagement userSessionManagement,
- NodesRegistrationManagement nodesRegistrationManagement, ConfidentialPortManager portManager,
- String errorPage) {
- super(deploymentContext, userSessionManagement, errorPage);
- this.nodesRegistrationManagement = nodesRegistrationManagement;
- this.portManager = portManager;
- }
-
- @Override
- protected Integer servePage(HttpServerExchange exchange, String location) {
- final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
- ServletRequest req = servletRequestContext.getServletRequest();
- ServletResponse resp = servletRequestContext.getServletResponse();
- RequestDispatcher disp = req.getRequestDispatcher(location);
- //make sure the login page is never cached
- exchange.getResponseHeaders().add(Headers.CACHE_CONTROL, "no-cache, no-store, must-revalidate");
- exchange.getResponseHeaders().add(Headers.PRAGMA, "no-cache");
- exchange.getResponseHeaders().add(Headers.EXPIRES, "0");
-
-
- try {
- disp.forward(req, resp);
- } catch (ServletException e) {
- throw new RuntimeException(e);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- return null;
- }
-
- @Override
- public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
- UndertowHttpFacade facade = createFacade(exchange);
- KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);
- if (!deployment.isConfigured()) {
- return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
- }
-
- nodesRegistrationManagement.tryRegister(deployment);
-
- RequestAuthenticator authenticator = createRequestAuthenticator(deployment, exchange, securityContext, facade);
-
- return keycloakAuthenticate(exchange, securityContext, authenticator);
- }
-
- protected RequestAuthenticator createRequestAuthenticator(KeycloakDeployment deployment, HttpServerExchange exchange, SecurityContext securityContext, UndertowHttpFacade facade) {
-
- int confidentialPort = getConfidentilPort(exchange);
- AdapterTokenStore tokenStore = getTokenStore(exchange, facade, deployment, securityContext);
- return new ServletRequestAuthenticator(facade, deployment,
- confidentialPort, securityContext, exchange, tokenStore);
- }
-
- protected int getConfidentilPort(HttpServerExchange exchange) {
- int confidentialPort = 8443;
- if (exchange.getRequestScheme().equalsIgnoreCase("HTTPS")) {
- confidentialPort = exchange.getHostPort();
- } else if (portManager != null) {
- confidentialPort = portManager.getConfidentialPort(exchange);
- }
- return confidentialPort;
- }
-
- @Override
- protected AdapterTokenStore getTokenStore(HttpServerExchange exchange, HttpFacade facade, KeycloakDeployment deployment, SecurityContext securityContext) {
- if (deployment.getTokenStore() == TokenStore.SESSION) {
- return new ServletSessionTokenStore(exchange, deployment, sessionManagement, securityContext);
- } else {
- return new UndertowCookieTokenStore(facade, deployment, securityContext);
- }
- }
-
- @Override
- public UndertowHttpFacade createFacade(HttpServerExchange exchange) {
- return new OIDCServletUndertowHttpFacade(exchange);
- }
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/ServletPreAuthActionsHandler.java b/container/src/main/java/org/keycloak/adapters/undertow/ServletPreAuthActionsHandler.java
deleted file mode 100644
index c9a91a3b3..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/ServletPreAuthActionsHandler.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.server.HandlerWrapper;
-import io.undertow.server.HttpHandler;
-import io.undertow.server.HttpServerExchange;
-import io.undertow.servlet.handlers.ServletRequestContext;
-import org.jboss.logging.Logger;
-import org.keycloak.adapters.AdapterDeploymentContext;
-import org.keycloak.adapters.PreAuthActionsHandler;
-import org.keycloak.adapters.undertow.SessionManagementBridge;
-import org.keycloak.adapters.undertow.UndertowHttpFacade;
-import org.keycloak.adapters.undertow.UndertowUserSessionManagement;
-
-/**
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class ServletPreAuthActionsHandler implements HttpHandler {
-
- private static final Logger log = Logger.getLogger(ServletPreAuthActionsHandler.class);
- protected HttpHandler next;
- protected UndertowUserSessionManagement userSessionManagement;
- protected AdapterDeploymentContext deploymentContext;
-
- public static class Wrapper implements HandlerWrapper {
- protected AdapterDeploymentContext deploymentContext;
- protected UndertowUserSessionManagement userSessionManagement;
-
-
- public Wrapper(AdapterDeploymentContext deploymentContext, UndertowUserSessionManagement userSessionManagement) {
- this.deploymentContext = deploymentContext;
- this.userSessionManagement = userSessionManagement;
- }
-
- @Override
- public HttpHandler wrap(HttpHandler handler) {
- return new ServletPreAuthActionsHandler(deploymentContext, userSessionManagement, handler);
- }
- }
-
- protected ServletPreAuthActionsHandler(AdapterDeploymentContext deploymentContext,
- UndertowUserSessionManagement userSessionManagement,
- HttpHandler next) {
- this.next = next;
- this.deploymentContext = deploymentContext;
- this.userSessionManagement = userSessionManagement;
- }
-
- @Override
- public void handleRequest(HttpServerExchange exchange) throws Exception {
- UndertowHttpFacade facade = new OIDCServletUndertowHttpFacade(exchange);
- final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
- SessionManagementBridge bridge = new SessionManagementBridge(userSessionManagement, servletRequestContext.getDeployment().getSessionManager());
- PreAuthActionsHandler handler = new PreAuthActionsHandler(bridge, deploymentContext, facade);
- if (handler.handleRequest()) return;
- next.handleRequest(exchange);
- }
-
-
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/ServletRequestAuthenticator.java b/container/src/main/java/org/keycloak/adapters/undertow/ServletRequestAuthenticator.java
deleted file mode 100644
index 6380c995e..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/ServletRequestAuthenticator.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.security.api.SecurityContext;
-import io.undertow.server.HttpServerExchange;
-import io.undertow.servlet.handlers.ServletRequestContext;
-import org.keycloak.KeycloakPrincipal;
-import org.keycloak.KeycloakSecurityContext;
-import org.keycloak.adapters.AdapterTokenStore;
-import org.keycloak.adapters.KeycloakDeployment;
-import org.keycloak.adapters.OAuthRequestAuthenticator;
-import org.keycloak.adapters.RefreshableKeycloakSecurityContext;
-import org.keycloak.adapters.spi.HttpFacade;
-import org.keycloak.adapters.undertow.ChangeSessionId;
-
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpSession;
-
-/**
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @author Stan Silvert [email protected] (C) 2014 Red Hat Inc.
- * @version $Revision: 1 $
- */
-public class ServletRequestAuthenticator extends AbstractUndertowRequestAuthenticator {
-
-
- public ServletRequestAuthenticator(HttpFacade facade, KeycloakDeployment deployment, int sslRedirectPort,
- SecurityContext securityContext, HttpServerExchange exchange,
- AdapterTokenStore tokenStore) {
- super(facade, deployment, sslRedirectPort, securityContext, exchange, tokenStore);
- }
-
- @Override
- protected OAuthRequestAuthenticator createOAuthAuthenticator() {
- return new OAuthRequestAuthenticator(this, facade, deployment, sslRedirectPort, tokenStore);
- }
-
- @Override
- protected void propagateKeycloakContext(KeycloakUndertowAccount account) {
- super.propagateKeycloakContext(account);
- final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
- HttpServletRequest req = (HttpServletRequest) servletRequestContext.getServletRequest();
- req.setAttribute(KeycloakSecurityContext.class.getName(), account.getKeycloakSecurityContext());
- }
-
- @Override
- protected KeycloakUndertowAccount createAccount(KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal) {
- return new KeycloakUndertowAccount(principal);
- }
-
- @Override
- protected String changeHttpSessionId(boolean create) {
- if (!deployment.isTurnOffChangeSessionIdOnLogin()) return ChangeSessionId.changeSessionId(exchange, create);
- else return getHttpSessionId(create);
- }
-
- protected String getHttpSessionId(boolean create) {
- HttpSession session = getSession(create);
- return session != null ? session.getId() : null;
- }
-
- protected HttpSession getSession(boolean create) {
- final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
- HttpServletRequest req = (HttpServletRequest) servletRequestContext.getServletRequest();
- return req.getSession(create);
- }
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/ServletSessionTokenStore.java b/container/src/main/java/org/keycloak/adapters/undertow/ServletSessionTokenStore.java
deleted file mode 100644
index 5b49b7fff..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/ServletSessionTokenStore.java
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.security.api.SecurityContext;
-import io.undertow.server.HttpServerExchange;
-import io.undertow.servlet.handlers.ServletRequestContext;
-import org.jboss.logging.Logger;
-import org.keycloak.KeycloakSecurityContext;
-import org.keycloak.adapters.*;
-import org.keycloak.adapters.undertow.SavedRequest;
-import org.keycloak.adapters.undertow.UndertowUserSessionManagement;
-
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpSession;
-
-/**
- * Per-request object. Storage of tokens in servlet HTTP session.
- *
- * @author <a href="mailto:[email protected]">Marek Posolda</a>
- */
-public class ServletSessionTokenStore implements AdapterTokenStore {
-
- protected static Logger log = Logger.getLogger(ServletSessionTokenStore.class);
-
- private final HttpServerExchange exchange;
- private final KeycloakDeployment deployment;
- private final UndertowUserSessionManagement sessionManagement;
- private final SecurityContext securityContext;
-
- public ServletSessionTokenStore(HttpServerExchange exchange, KeycloakDeployment deployment, UndertowUserSessionManagement sessionManagement,
- SecurityContext securityContext) {
- this.exchange = exchange;
- this.deployment = deployment;
- this.sessionManagement = sessionManagement;
- this.securityContext = securityContext;
- }
-
- @Override
- public void checkCurrentToken() {
- // no-op on undertow
- }
-
- @Override
- public boolean isCached(RequestAuthenticator authenticator) {
- HttpSession session = getSession(false);
- if (session == null) {
- log.debug("session was null, returning null");
- return false;
- }
- KeycloakUndertowAccount account = null;
- try {
- account = (KeycloakUndertowAccount)session.getAttribute(KeycloakUndertowAccount.class.getName());
- } catch (IllegalStateException e) {
- log.debug("session was invalidated. Return false.");
- return false;
- }
- if (account == null) {
- log.debug("Account was not in session, returning null");
- return false;
- }
-
- if (!deployment.getRealm().equals(account.getKeycloakSecurityContext().getRealm())) {
- log.debug("Account in session belongs to a different realm than for this request.");
- return false;
- }
-
- account.setCurrentRequestInfo(deployment, this);
- if (account.checkActive()) {
- log.debug("Cached account found");
- securityContext.authenticationComplete(account, "KEYCLOAK", false);
- ((AbstractUndertowRequestAuthenticator)authenticator).propagateKeycloakContext(account);
- restoreRequest();
- return true;
- } else {
- log.debug("Refresh failed. Account was not active. Returning null and invalidating Http session");
- try {
- session.removeAttribute(KeycloakUndertowAccount.class.getName());
- session.removeAttribute(KeycloakSecurityContext.class.getName());
- session.invalidate();
- } catch (Exception e) {
- log.debug("Failed to invalidate session, might already be invalidated");
- }
- return false;
- }
- }
-
- @Override
- public void saveAccountInfo(OidcKeycloakAccount account) {
- final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
- HttpSession session = getSession(true);
- session.setAttribute(KeycloakUndertowAccount.class.getName(), account);
- session.setAttribute(KeycloakSecurityContext.class.getName(), account.getKeycloakSecurityContext());
- sessionManagement.login(servletRequestContext.getDeployment().getSessionManager());
- }
-
- @Override
- public void logout() {
- final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
- HttpServletRequest req = (HttpServletRequest) servletRequestContext.getServletRequest();
- req.removeAttribute(KeycloakUndertowAccount.class.getName());
- req.removeAttribute(KeycloakSecurityContext.class.getName());
- HttpSession session = req.getSession(false);
- if (session == null) return;
- try {
- KeycloakUndertowAccount account = (KeycloakUndertowAccount) session.getAttribute(KeycloakUndertowAccount.class.getName());
- if (account == null) return;
- session.removeAttribute(KeycloakSecurityContext.class.getName());
- session.removeAttribute(KeycloakUndertowAccount.class.getName());
- } catch (IllegalStateException ise) {
- // Session may be already logged-out in case that app has adminUrl
- log.debugf("Session %s logged-out already", session.getId());
- }
- }
-
- @Override
- public void refreshCallback(RefreshableKeycloakSecurityContext securityContext) {
- // no-op
- }
-
- @Override
- public void saveRequest() {
- SavedRequest.trySaveRequest(exchange);
-
- }
-
- @Override
- public boolean restoreRequest() {
- HttpSession session = getSession(false);
- if (session == null) return false;
- SavedRequest.tryRestoreRequest(exchange, session);
- return false;
- }
-
- protected HttpSession getSession(boolean create) {
- final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
- HttpServletRequest req = (HttpServletRequest) servletRequestContext.getServletRequest();
- return req.getSession(create);
- }
-
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/SessionManagementBridge.java b/container/src/main/java/org/keycloak/adapters/undertow/SessionManagementBridge.java
deleted file mode 100644
index fcde53737..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/SessionManagementBridge.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.server.session.SessionManager;
-import org.keycloak.adapters.spi.UserSessionManagement;
-
-import java.util.List;
-
-/**
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class SessionManagementBridge implements UserSessionManagement {
-
- protected UndertowUserSessionManagement userSessionManagement;
- protected SessionManager sessionManager;
-
- public SessionManagementBridge(UndertowUserSessionManagement userSessionManagement, SessionManager sessionManager) {
- this.userSessionManagement = userSessionManagement;
- this.sessionManager = sessionManager;
- }
-
- @Override
- public void logoutAll() {
- userSessionManagement.logoutAll(sessionManager);
- }
-
- @Override
- public void logoutHttpSessions(List<String> ids) {
- userSessionManagement.logoutHttpSessions(sessionManager, ids);
- }
-
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/UndertowAuthenticatedActionsHandler.java b/container/src/main/java/org/keycloak/adapters/undertow/UndertowAuthenticatedActionsHandler.java
deleted file mode 100644
index b7ed15400..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/UndertowAuthenticatedActionsHandler.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.server.HandlerWrapper;
-import io.undertow.server.HttpHandler;
-import io.undertow.server.HttpServerExchange;
-import org.jboss.logging.Logger;
-import org.keycloak.adapters.AdapterDeploymentContext;
-import org.keycloak.adapters.AuthenticatedActionsHandler;
-import org.keycloak.adapters.KeycloakDeployment;
-
-/**
- * Bridge for authenticated Keycloak adapter actions
- *
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @author Stan Silvert [email protected] (C) 2014 Red Hat Inc.
- * @version $Revision: 1 $
- */
-public class UndertowAuthenticatedActionsHandler implements HttpHandler {
- private static final Logger log = Logger.getLogger(UndertowAuthenticatedActionsHandler.class);
- protected AdapterDeploymentContext deploymentContext;
- protected HttpHandler next;
-
- public static class Wrapper implements HandlerWrapper {
- protected AdapterDeploymentContext deploymentContext;
-
- public Wrapper(AdapterDeploymentContext deploymentContext) {
- this.deploymentContext = deploymentContext;
- }
-
- @Override
- public HttpHandler wrap(HttpHandler handler) {
- return new UndertowAuthenticatedActionsHandler(deploymentContext, handler);
- }
- }
-
-
- public UndertowAuthenticatedActionsHandler(AdapterDeploymentContext deploymentContext, HttpHandler next) {
- this.deploymentContext = deploymentContext;
- this.next = next;
- }
-
- @Override
- public void handleRequest(HttpServerExchange exchange) throws Exception {
- OIDCUndertowHttpFacade facade = new OIDCUndertowHttpFacade(exchange);
- KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);
- if (deployment != null && deployment.isConfigured()) {
- AuthenticatedActionsHandler handler = new AuthenticatedActionsHandler(deployment, facade);
- if (handler.handledRequest()) return;
- }
- next.handleRequest(exchange);
- }
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/UndertowAuthenticationMechanism.java b/container/src/main/java/org/keycloak/adapters/undertow/UndertowAuthenticationMechanism.java
deleted file mode 100644
index 27aa3be29..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/UndertowAuthenticationMechanism.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.security.api.SecurityContext;
-import io.undertow.server.HttpServerExchange;
-import org.keycloak.adapters.*;
-import org.keycloak.adapters.undertow.UndertowHttpFacade;
-import org.keycloak.adapters.undertow.UndertowUserSessionManagement;
-
-/**
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class UndertowAuthenticationMechanism extends AbstractUndertowKeycloakAuthMech {
- protected NodesRegistrationManagement nodesRegistrationManagement;
- protected int confidentialPort;
-
- public UndertowAuthenticationMechanism(AdapterDeploymentContext deploymentContext, UndertowUserSessionManagement sessionManagement,
- NodesRegistrationManagement nodesRegistrationManagement, int confidentialPort, String errorPage) {
- super(deploymentContext, sessionManagement, errorPage);
- this.nodesRegistrationManagement = nodesRegistrationManagement;
- this.confidentialPort = confidentialPort;
- }
-
- @Override
- public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
- UndertowHttpFacade facade = createFacade(exchange);
- KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);
- if (!deployment.isConfigured()) {
- return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
- }
-
- nodesRegistrationManagement.tryRegister(deployment);
-
- AdapterTokenStore tokenStore = getTokenStore(exchange, facade, deployment, securityContext);
- RequestAuthenticator authenticator = new UndertowRequestAuthenticator(facade, deployment, confidentialPort, securityContext, exchange, tokenStore);
-
- return keycloakAuthenticate(exchange, securityContext, authenticator);
- }
-
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/UndertowCookieTokenStore.java b/container/src/main/java/org/keycloak/adapters/undertow/UndertowCookieTokenStore.java
deleted file mode 100644
index 270454777..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/UndertowCookieTokenStore.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.security.api.SecurityContext;
-import org.jboss.logging.Logger;
-import org.keycloak.KeycloakPrincipal;
-import org.keycloak.adapters.*;
-import org.keycloak.adapters.spi.HttpFacade;
-
-/**
- * Per-request object. Storage of tokens in cookie
- *
- * @author <a href="mailto:[email protected]">Marek Posolda</a>
- */
-public class UndertowCookieTokenStore implements AdapterTokenStore {
-
- protected static Logger log = Logger.getLogger(UndertowCookieTokenStore.class);
-
- private final HttpFacade facade;
- private final KeycloakDeployment deployment;
- private final SecurityContext securityContext;
-
- public UndertowCookieTokenStore(HttpFacade facade, KeycloakDeployment deployment,
- SecurityContext securityContext) {
- this.facade = facade;
- this.deployment = deployment;
- this.securityContext = securityContext;
- }
-
- @Override
- public void checkCurrentToken() {
- // no-op on undertow
- }
-
- @Override
- public boolean isCached(RequestAuthenticator authenticator) {
- KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = CookieTokenStore.getPrincipalFromCookie(deployment, facade, this);
- if (principal == null) {
- log.debug("Account was not in cookie or was invalid, returning null");
- return false;
- }
- KeycloakUndertowAccount account = new KeycloakUndertowAccount(principal);
-
- if (!deployment.getRealm().equals(account.getKeycloakSecurityContext().getRealm())) {
- log.debug("Account in session belongs to a different realm than for this request.");
- return false;
- }
-
- if (account.checkActive()) {
- log.debug("Cached account found");
- securityContext.authenticationComplete(account, "KEYCLOAK", false);
- ((AbstractUndertowRequestAuthenticator)authenticator).propagateKeycloakContext(account);
- return true;
- } else {
- log.debug("Account was not active, removing cookie and returning false");
- CookieTokenStore.removeCookie(deployment, facade);
- return false;
- }
- }
-
- @Override
- public void saveAccountInfo(OidcKeycloakAccount account) {
- RefreshableKeycloakSecurityContext secContext = (RefreshableKeycloakSecurityContext)account.getKeycloakSecurityContext();
- CookieTokenStore.setTokenCookie(deployment, facade, secContext);
- }
-
- @Override
- public void logout() {
- KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = CookieTokenStore.getPrincipalFromCookie(deployment, facade, this);
- if (principal == null) return;
-
- CookieTokenStore.removeCookie(deployment, facade);
- }
-
- @Override
- public void refreshCallback(RefreshableKeycloakSecurityContext securityContext) {
- CookieTokenStore.setTokenCookie(deployment, facade, securityContext);
- }
-
- @Override
- public void saveRequest() {
-
- }
-
- @Override
- public boolean restoreRequest() {
- return false;
- }
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/UndertowHttpFacade.java b/container/src/main/java/org/keycloak/adapters/undertow/UndertowHttpFacade.java
deleted file mode 100644
index fa18e8b96..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/UndertowHttpFacade.java
+++ /dev/null
@@ -1,333 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.server.HttpServerExchange;
-import io.undertow.server.handlers.CookieImpl;
-import io.undertow.server.handlers.form.FormData;
-import io.undertow.server.handlers.form.FormData.FormValue;
-import io.undertow.server.handlers.form.FormDataParser;
-import io.undertow.server.handlers.form.FormParserFactory;
-import io.undertow.servlet.handlers.ServletRequestContext;
-import io.undertow.util.AttachmentKey;
-import io.undertow.util.Headers;
-import io.undertow.util.HttpString;
-import jakarta.servlet.ReadListener;
-import org.keycloak.adapters.spi.AuthenticationError;
-import org.keycloak.adapters.spi.HttpFacade;
-import org.keycloak.adapters.spi.LogoutError;
-import org.keycloak.common.util.KeycloakUriBuilder;
-
-import java.security.cert.X509Certificate;
-import jakarta.servlet.ServletInputStream;
-import jakarta.servlet.ServletRequest;
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletRequestWrapper;
-import java.io.BufferedInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.util.Deque;
-import java.util.List;
-import java.util.Map;
-
-/**
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class UndertowHttpFacade implements HttpFacade {
- public static final AttachmentKey<AuthenticationError> AUTH_ERROR_ATTACHMENT_KEY = AttachmentKey.create(AuthenticationError.class);
- public static final AttachmentKey<LogoutError> LOGOUT_ERROR_ATTACHMENT_KEY = AttachmentKey.create(LogoutError.class);
-
- protected HttpServerExchange exchange;
- protected RequestFacade requestFacade = new RequestFacade();
- protected ResponseFacade responseFacade = new ResponseFacade();
-
- public UndertowHttpFacade(HttpServerExchange exchange) {
- this.exchange = exchange;
- }
-
- @Override
- public Request getRequest() {
- return requestFacade;
- }
-
- @Override
- public Response getResponse() {
- return responseFacade;
- }
-
- @Override
- public X509Certificate[] getCertificateChain() {
- X509Certificate[] chain = new X509Certificate[0];
- try {
- chain = (X509Certificate[]) exchange.getConnection().getSslSessionInfo().getPeerCertificates();
- } catch (Exception ignore) {
-
- }
- return chain;
- }
-
- protected class RequestFacade implements Request {
-
- private InputStream inputStream;
- private final FormParserFactory formParserFactory = FormParserFactory.builder().build();
- private FormData formData;
-
- @Override
- public String getURI() {
- KeycloakUriBuilder uriBuilder = KeycloakUriBuilder.fromUri(exchange.getRequestURI())
- .replaceQuery(exchange.getQueryString());
- if (!exchange.isHostIncludedInRequestURI()) uriBuilder.scheme(exchange.getRequestScheme()).host(exchange.getHostAndPort());
- return uriBuilder.buildAsString();
- }
-
- @Override
- public String getRelativePath() {
- return exchange.getRelativePath();
- }
-
- @Override
- public boolean isSecure() {
- String protocol = exchange.getRequestScheme();
- return protocol.equalsIgnoreCase("https");
- }
-
- @Override
- public String getFirstParam(String param) {
- Deque<String> values = exchange.getQueryParameters().get(param);
-
- if (values != null && !values.isEmpty()) {
- return values.getFirst();
- }
-
- if (formData == null && "post".equalsIgnoreCase(getMethod())) {
- FormDataParser parser = formParserFactory.createParser(exchange);
- try {
- formData = parser.parseBlocking();
- } catch (IOException cause) {
- throw new RuntimeException("Failed to parse form parameters", cause);
- }
- }
-
- if (formData != null) {
- Deque<FormValue> formValues = formData.get(param);
-
- if (formValues != null && !formValues.isEmpty()) {
- FormValue firstValue = formValues.getFirst();
-
- if (!firstValue.isFileItem()) {
- return firstValue.getValue();
- }
- }
- }
-
- return null;
- }
-
- @Override
- public String getQueryParamValue(String param) {
- Map<String,Deque<String>> queryParameters = exchange.getQueryParameters();
- if (queryParameters == null) return null;
- Deque<String> strings = queryParameters.get(param);
- if (strings == null) return null;
- return strings.getFirst();
- }
-
- @SuppressWarnings("removal")
- @Override
- public Cookie getCookie(String cookieName) {
- Map<String, io.undertow.server.handlers.Cookie> requestCookies = exchange.getRequestCookies();
- if (requestCookies == null) return null;
- io.undertow.server.handlers.Cookie cookie = requestCookies.get(cookieName);
- if (cookie == null) return null;
- return new Cookie(cookie.getName(), cookie.getValue(), cookie.getVersion(), cookie.getDomain(), cookie.getPath());
- }
-
- @Override
- public List<String> getHeaders(String name) {
- return exchange.getRequestHeaders().get(name);
- }
-
- @Override
- public String getMethod() {
- return exchange.getRequestMethod().toString();
- }
-
-
-
- @Override
- public String getHeader(String name) {
- return exchange.getRequestHeaders().getFirst(name);
- }
-
- @Override
- public InputStream getInputStream() {
- return getInputStream(false);
- }
-
- @Override
- public InputStream getInputStream(boolean buffered) {
- if (!exchange.isBlocking()) exchange.startBlocking();
-
- if (inputStream != null) {
- return inputStream;
- }
-
- if (buffered) {
- ServletRequestContext context = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
- ServletRequest servletRequest = context.getServletRequest();
-
- inputStream = new BufferedInputStream(exchange.getInputStream());
-
- context.setServletRequest(new HttpServletRequestWrapper((HttpServletRequest) servletRequest) {
- @Override
- public ServletInputStream getInputStream() {
- inputStream.mark(0);
- return new ServletInputStream() {
- @Override
- public boolean isFinished() {
- try {
- return inputStream.available() == 0;
- } catch (IOException ignored) {
- }
- return true;
- }
-
- @Override
- public boolean isReady() {
- try {
- return inputStream.available() > 0;
- } catch (IOException ignored) {
- }
- return false;
- }
-
- @Override
- public void setReadListener(ReadListener readListener) {
-
- }
-
- @Override
- public int read() throws IOException {
- return inputStream.read();
- }
- };
- }
- });
- return inputStream;
- }
-
- return exchange.getInputStream();
- }
-
- @Override
- public String getRemoteAddr() {
- InetSocketAddress sourceAddress = exchange.getSourceAddress();
- if (sourceAddress == null) {
- return "";
- }
- InetAddress address = sourceAddress.getAddress();
- if (address == null) {
- // this is unresolved, so we just return the host name not exactly spec, but if the name should be
- // resolved then a PeerNameResolvingHandler should be used and this is probably better than just
- // returning null
- return sourceAddress.getHostString();
- }
- return address.getHostAddress();
- }
-
- @Override
- public void setError(AuthenticationError error) {
- exchange.putAttachment(AUTH_ERROR_ATTACHMENT_KEY, error);
- }
-
- @Override
- public void setError(LogoutError error) {
- exchange.putAttachment(LOGOUT_ERROR_ATTACHMENT_KEY, error);
-
- }
- }
-
- protected class ResponseFacade implements Response {
- @Override
- public void setStatus(int status) {
- exchange.setStatusCode(status);
- }
-
- @Override
- public void addHeader(String name, String value) {
- exchange.getResponseHeaders().add(new HttpString(name), value);
- }
-
- @Override
- public void setHeader(String name, String value) {
- exchange.getResponseHeaders().put(new HttpString(name), value);
- }
-
- @Override
- public void resetCookie(String name, String path) {
- CookieImpl cookie = new CookieImpl(name, "");
- cookie.setMaxAge(0);
- cookie.setPath(path);
- exchange.setResponseCookie(cookie);
- }
-
- @Override
- public void setCookie(String name, String value, String path, String domain, int maxAge, boolean secure, boolean httpOnly) {
- CookieImpl cookie = new CookieImpl(name, value);
- cookie.setPath(path);
- cookie.setDomain(domain);
- cookie.setMaxAge(maxAge);
- cookie.setSecure(secure);
- cookie.setHttpOnly(httpOnly);
- exchange.setResponseCookie(cookie);
- }
-
- @Override
- public OutputStream getOutputStream() {
- if (!exchange.isBlocking()) exchange.startBlocking();
- return exchange.getOutputStream();
- }
-
- @Override
- public void sendError(int code) {
- exchange.setStatusCode(code);
- }
-
- @Override
- public void sendError(int code, String message) {
- exchange.setStatusCode(code);
- exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html");
- try {
- exchange.getOutputStream().write(message.getBytes());
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- exchange.endExchange();
- }
-
-
- @Override
- public void end() {
- exchange.endExchange();
- }
- }
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/UndertowNodesRegistrationManagementWrapper.java b/container/src/main/java/org/keycloak/adapters/undertow/UndertowNodesRegistrationManagementWrapper.java
deleted file mode 100644
index f25726123..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/UndertowNodesRegistrationManagementWrapper.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import org.keycloak.adapters.NodesRegistrationManagement;
-
-import jakarta.servlet.ServletContextEvent;
-import jakarta.servlet.ServletContextListener;
-
-/**
- * @author <a href="mailto:[email protected]">Marek Posolda</a>
- */
-public class UndertowNodesRegistrationManagementWrapper implements ServletContextListener {
-
- private final NodesRegistrationManagement delegate;
-
- public UndertowNodesRegistrationManagementWrapper(NodesRegistrationManagement delegate) {
- this.delegate = delegate;
- }
-
- @Override
- public void contextInitialized(ServletContextEvent sce) {
- }
-
- @Override
- public void contextDestroyed(ServletContextEvent sce) {
- delegate.stop();
- }
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/UndertowPreAuthActionsHandler.java b/container/src/main/java/org/keycloak/adapters/undertow/UndertowPreAuthActionsHandler.java
deleted file mode 100644
index be234587c..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/UndertowPreAuthActionsHandler.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.server.HttpHandler;
-import io.undertow.server.HttpServerExchange;
-import io.undertow.server.session.SessionManager;
-import org.jboss.logging.Logger;
-import org.keycloak.adapters.AdapterDeploymentContext;
-import org.keycloak.adapters.PreAuthActionsHandler;
-import org.keycloak.adapters.undertow.SessionManagementBridge;
-import org.keycloak.adapters.undertow.UndertowHttpFacade;
-import org.keycloak.adapters.undertow.UndertowUserSessionManagement;
-
-/**
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class UndertowPreAuthActionsHandler implements HttpHandler {
-
- private static final Logger log = Logger.getLogger(UndertowPreAuthActionsHandler.class);
- protected HttpHandler next;
- protected SessionManager sessionManager;
- protected UndertowUserSessionManagement userSessionManagement;
- protected AdapterDeploymentContext deploymentContext;
-
- public UndertowPreAuthActionsHandler(AdapterDeploymentContext deploymentContext,
- UndertowUserSessionManagement userSessionManagement,
- SessionManager sessionManager,
- HttpHandler next) {
- this.next = next;
- this.deploymentContext = deploymentContext;
- this.sessionManager = sessionManager;
- this.userSessionManagement = userSessionManagement;
- }
-
- @Override
- public void handleRequest(HttpServerExchange exchange) throws Exception {
- UndertowHttpFacade facade = createFacade(exchange);
- SessionManagementBridge bridge = new SessionManagementBridge(userSessionManagement, sessionManager);
- PreAuthActionsHandler handler = new PreAuthActionsHandler(bridge, deploymentContext, facade);
- if (handler.handleRequest()) return;
- next.handleRequest(exchange);
- }
-
- public UndertowHttpFacade createFacade(HttpServerExchange exchange) {
- return new OIDCUndertowHttpFacade(exchange);
- }
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/UndertowRequestAuthenticator.java b/container/src/main/java/org/keycloak/adapters/undertow/UndertowRequestAuthenticator.java
deleted file mode 100644
index 26f358378..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/UndertowRequestAuthenticator.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.security.api.SecurityContext;
-import io.undertow.server.HttpServerExchange;
-import org.keycloak.KeycloakPrincipal;
-import org.keycloak.adapters.AdapterTokenStore;
-import org.keycloak.adapters.KeycloakDeployment;
-import org.keycloak.adapters.RefreshableKeycloakSecurityContext;
-import org.keycloak.adapters.spi.HttpFacade;
-
-/**
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class UndertowRequestAuthenticator extends AbstractUndertowRequestAuthenticator {
- public UndertowRequestAuthenticator(HttpFacade facade, KeycloakDeployment deployment, int sslRedirectPort,
- SecurityContext securityContext, HttpServerExchange exchange, AdapterTokenStore tokenStore) {
- super(facade, deployment, sslRedirectPort, securityContext, exchange, tokenStore);
- }
-
- @Override
- protected KeycloakUndertowAccount createAccount(KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal) {
- return new KeycloakUndertowAccount(principal);
- }
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/UndertowSessionTokenStore.java b/container/src/main/java/org/keycloak/adapters/undertow/UndertowSessionTokenStore.java
deleted file mode 100644
index f290c002b..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/UndertowSessionTokenStore.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.security.api.SecurityContext;
-import io.undertow.server.HttpServerExchange;
-import io.undertow.server.session.Session;
-import io.undertow.util.Sessions;
-import org.jboss.logging.Logger;
-import org.keycloak.KeycloakSecurityContext;
-import org.keycloak.adapters.*;
-import org.keycloak.adapters.undertow.UndertowUserSessionManagement;
-
-/**
- * Per-request object. Storage of tokens in undertow session.
- *
- * @author <a href="mailto:[email protected]">Marek Posolda</a>
- */
-public class UndertowSessionTokenStore implements AdapterTokenStore {
-
- protected static Logger log = Logger.getLogger(UndertowSessionTokenStore.class);
-
- private final HttpServerExchange exchange;
- private final KeycloakDeployment deployment;
- private final UndertowUserSessionManagement sessionManagement;
- private final SecurityContext securityContext;
-
- public UndertowSessionTokenStore(HttpServerExchange exchange, KeycloakDeployment deployment, UndertowUserSessionManagement sessionManagement,
- SecurityContext securityContext) {
- this.exchange = exchange;
- this.deployment = deployment;
- this.sessionManagement = sessionManagement;
- this.securityContext = securityContext;
- }
-
- @Override
- public void checkCurrentToken() {
- // no-op on undertow
- }
-
- @Override
- public boolean isCached(RequestAuthenticator authenticator) {
- Session session = Sessions.getSession(exchange);
- if (session == null) {
- log.debug("session was null, returning null");
- return false;
- }
- KeycloakUndertowAccount account = (KeycloakUndertowAccount)session.getAttribute(KeycloakUndertowAccount.class.getName());
- if (account == null) {
- log.debug("Account was not in session, returning null");
- return false;
- }
-
- if (!deployment.getRealm().equals(account.getKeycloakSecurityContext().getRealm())) {
- log.debug("Account in session belongs to a different realm than for this request.");
- return false;
- }
-
- account.setCurrentRequestInfo(deployment, this);
- if (account.checkActive()) {
- log.debug("Cached account found");
- securityContext.authenticationComplete(account, "KEYCLOAK", false);
- ((AbstractUndertowRequestAuthenticator)authenticator).propagateKeycloakContext(account);
- return true;
- } else {
- log.debug("Account was not active, returning false");
- session.removeAttribute(KeycloakUndertowAccount.class.getName());
- session.removeAttribute(KeycloakSecurityContext.class.getName());
- session.invalidate(exchange);
- return false;
- }
- }
-
- @Override
- public void saveRequest() {
-
- }
-
- @Override
- public boolean restoreRequest() {
- return false;
- }
-
- @Override
- public void saveAccountInfo(OidcKeycloakAccount account) {
- Session session = Sessions.getOrCreateSession(exchange);
- session.setAttribute(KeycloakUndertowAccount.class.getName(), account);
- session.setAttribute(KeycloakSecurityContext.class.getName(), account.getKeycloakSecurityContext());
- sessionManagement.login(session.getSessionManager());
- }
-
- @Override
- public void logout() {
- Session session = Sessions.getSession(exchange);
- if (session == null) return;
- KeycloakUndertowAccount account = (KeycloakUndertowAccount)session.getAttribute(KeycloakUndertowAccount.class.getName());
- if (account == null) return;
- session.removeAttribute(KeycloakUndertowAccount.class.getName());
- session.removeAttribute(KeycloakSecurityContext.class.getName());
- }
-
- @Override
- public void refreshCallback(RefreshableKeycloakSecurityContext securityContext) {
- // no-op
- }
-}
diff --git a/container/src/main/java/org/keycloak/adapters/undertow/UndertowUserSessionManagement.java b/container/src/main/java/org/keycloak/adapters/undertow/UndertowUserSessionManagement.java
deleted file mode 100644
index 953080c21..000000000
--- a/container/src/main/java/org/keycloak/adapters/undertow/UndertowUserSessionManagement.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.keycloak.adapters.undertow;
-
-import io.undertow.server.HttpServerExchange;
-import io.undertow.server.session.Session;
-import io.undertow.server.session.SessionConfig;
-import io.undertow.server.session.SessionListener;
-import io.undertow.server.session.SessionManager;
-import org.jboss.logging.Logger;
-
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-
-/**
- * Manages relationship to users and sessions so that forced admin logout can be implemented
- *
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class UndertowUserSessionManagement implements SessionListener {
- private static final Logger log = Logger.getLogger(UndertowUserSessionManagement.class);
- protected volatile boolean registered;
- private final ExecutorService executor = Executors.newSingleThreadExecutor();
-
- public void login(SessionManager manager) {
- if (!registered) {
- manager.registerSessionListener(this);
- registered = true;
- }
- }
-
- /**
- * This method runs the given runnable in the current thread if the session manager does not use distributed sessions,
- * or in a separate thread if it does. This is to work around:
- * <pre>
- * org.infinispan.util.concurrent.TimeoutException: ISPN000299: Unable to acquire lock after 15 seconds for key SessionCreationMetaDataKey
- * </pre>
- * See https://issues.jboss.org/browse/KEYCLOAK-9822
- * @param r
- */
- private void workaroundIspnDeadlock(final SessionManager manager, Runnable r) {
- if (manager.getClass().getName().equals("org.wildfly.clustering.web.undertow.session.DistributableSessionManager")) {
- executor.submit(r);
- } else {
- r.run();
- }
- }
-
- public void logoutAll(final SessionManager manager) {
- final Set<String> allSessions = manager.getAllSessions();
- workaroundIspnDeadlock(manager, new Runnable() {
- @Override
- public void run() {
- for (String sessionId : allSessions) logoutSession(manager, sessionId);
- }
- });
- }
-
- public void logoutHttpSessions(final SessionManager manager, final List<String> sessionIds) {
- log.debugf("logoutHttpSessions: %s", sessionIds);
-
- workaroundIspnDeadlock(manager, new Runnable() {
- @Override
- public void run() {
- for (String sessionId : sessionIds) {
- logoutSession(manager, sessionId);
- }
- }
- });
- }
-
- protected void logoutSession(SessionManager manager, String httpSessionId) {
- log.debugf("logoutHttpSession: %s", httpSessionId);
- Session session = getSessionById(manager, httpSessionId);
- try {
- if (session != null) session.invalidate(null);
- } catch (Exception e) {
- log.warnf("Session %s not present or already invalidated.", httpSessionId);
- }
- }
-
- protected Session getSessionById(SessionManager manager, final String sessionId) {
- // TODO: Workaround for WFLY-3345. Remove this once we move to wildfly 8.2
- if (manager.getClass().getName().equals("org.wildfly.clustering.web.undertow.session.DistributableSessionManager")) {
- return manager.getSession(null, new SessionConfig() {
-
- @Override
- public void setSessionId(HttpServerExchange exchange, String sessionId) {
- }
-
- @Override
- public void clearSession(HttpServerExchange exchange, String sessionId) {
- }
-
- @Override
- public String findSessionId(HttpServerExchange exchange) {
- return sessionId;
- }
-
- @Override
- public SessionCookieSource sessionCookieSource(HttpServerExchange exchange) {
- return null;
- }
-
- @Override
- public String rewriteUrl(String originalUrl, String sessionId) {
- return null;
- }
-
- });
-
- } else {
- return manager.getSession(sessionId);
- }
- }
-
-
- @Override
- public void sessionCreated(Session session, HttpServerExchange exchange) {
- }
-
- @Override
- public void sessionDestroyed(Session session, HttpServerExchange exchange, SessionDestroyedReason reason) {
- }
-
-
- @Override
- public void sessionIdChanged(Session session, String oldSessionId) {
- }
-
- @Override
- public void attributeAdded(Session session, String name, Object value) {
- }
-
- @Override
- public void attributeUpdated(Session session, String name, Object newValue, Object oldValue) {
- }
-
- @Override
- public void attributeRemoved(Session session, String name, Object oldValue) {
- }
-
-}
diff --git a/container/src/main/java/org/openremote/container/security/AuthContext.java b/container/src/main/java/org/openremote/container/security/AuthContext.java
index 1e4ec881d..ed2267563 100644
--- a/container/src/main/java/org/openremote/container/security/AuthContext.java
+++ b/container/src/main/java/org/openremote/container/security/AuthContext.java
@@ -21,11 +21,13 @@ package org.openremote.container.security;
import org.openremote.model.Constants;
import org.openremote.model.security.User;
+import org.openremote.model.util.TextUtil;
+
+import static org.openremote.model.Constants.RESTRICTED_USER_REALM_ROLE;
/**
* Services should use this interface to access a user's identity and perform authorization checks.
*/
-// TODO: Remove this and just use AccessToken from Subject's KeycloakPrincipal
public interface AuthContext {
String getAuthenticatedRealmName();
@@ -43,6 +45,10 @@ public interface AuthContext {
return Constants.MASTER_REALM.equals(getAuthenticatedRealmName()) && hasRealmRole(Constants.SUPER_USER_REALM_ROLE);
}
+ default boolean isRestrictedUser() {
+ return hasRealmRole(RESTRICTED_USER_REALM_ROLE);
+ }
+
default boolean isServiceAccount() {
String username = getUsername();
return username != null && username.startsWith(User.SERVICE_ACCOUNT_PREFIX);
@@ -60,6 +66,6 @@ public interface AuthContext {
* @return <code>true</code> if the user is authenticated in the same realm or if the user is the superuser (admin).
*/
default boolean isRealmAccessibleByUser(String realm) {
- return realm != null && realm.length() > 0 && (realm.equals(getAuthenticatedRealmName()) || isSuperUser());
+ return !TextUtil.isNullOrEmpty(realm) && (isSuperUser() || realm.equals(getAuthenticatedRealmName()));
}
}
diff --git a/container/src/main/java/org/openremote/container/security/IdentityProvider.java b/container/src/main/java/org/openremote/container/security/IdentityProvider.java
index 7579532cd..8b22a4080 100644
--- a/container/src/main/java/org/openremote/container/security/IdentityProvider.java
+++ b/container/src/main/java/org/openremote/container/security/IdentityProvider.java
@@ -19,13 +19,20 @@
*/
package org.openremote.container.security;
-import io.undertow.servlet.api.DeploymentInfo;
+import jakarta.security.enterprise.AuthenticationException;
+import jakarta.servlet.FilterRegistration;
+import jakarta.servlet.ServletContext;
import org.openremote.model.Container;
+import javax.security.auth.Subject;
+import java.security.Principal;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+
/**
* SPI for implementations used by {@link IdentityService}.
*/
-public interface IdentityProvider {
+public interface IdentityProvider extends TokenVerifier {
String OR_ADMIN_PASSWORD = "OR_ADMIN_PASSWORD";
String OR_ADMIN_PASSWORD_DEFAULT = "secret";
@@ -36,5 +43,24 @@ public interface IdentityProvider {
void stop(Container container) throws Exception;
- void secureDeployment(DeploymentInfo deploymentInfo);
+ FilterRegistration.Dynamic secureDeployment(ServletContext servletContext);
+
+ /**
+ * Retrieves a bearer token for the given realm, client id and client secret using this {@link IdentityProvider}.
+ * Only {@link jakarta.security.enterprise.AuthenticationException} should be thrown.
+ */
+ CompletableFuture<OIDCTokenResponse> authenticate(String realm, String clientId, String clientSecret) throws AuthenticationException;
+
+ static String getSubjectId(Subject subject) {
+ return Optional.ofNullable(getTokenPrincipal(subject)).map(Principal::getName).orElse(null);
+ }
+
+ static TokenPrincipal getTokenPrincipal(Subject subject) {
+ if (subject == null || subject.getPrincipals() == null) {
+ return null;
+ }
+
+ return subject.getPrincipals().stream().filter(p -> p instanceof TokenPrincipal)
+ .map(p -> (TokenPrincipal)p).findFirst().orElse(null);
+ }
}
diff --git a/container/src/main/java/org/openremote/container/security/IdentityService.java b/container/src/main/java/org/openremote/container/security/IdentityService.java
index 22cd00a76..19be59060 100644
--- a/container/src/main/java/org/openremote/container/security/IdentityService.java
+++ b/container/src/main/java/org/openremote/container/security/IdentityService.java
@@ -19,15 +19,18 @@
*/
package org.openremote.container.security;
-import io.undertow.servlet.api.DeploymentInfo;
+import jakarta.security.enterprise.AuthenticationException;
+import jakarta.servlet.FilterRegistration;
+import jakarta.servlet.ServletContext;
import org.openremote.container.persistence.PersistenceService;
import org.openremote.container.security.keycloak.KeycloakIdentityProvider;
import org.openremote.model.Container;
import org.openremote.model.ContainerService;
+import java.util.concurrent.CompletableFuture;
import java.util.logging.Logger;
-public abstract class IdentityService implements ContainerService {
+public abstract class IdentityService implements ContainerService, TokenVerifier {
public static final int PRIORITY = PersistenceService.PRIORITY + 10;
private static final Logger LOG = Logger.getLogger(IdentityService.class.getName());
@@ -60,10 +63,9 @@ public abstract class IdentityService implements ContainerService {
identityProvider.stop(container);
}
- public void secureDeployment(DeploymentInfo deploymentInfo) {
- LOG.info("Securing web deployment: " + deploymentInfo.getContextPath());
- deploymentInfo.setSecurityDisabled(false);
- identityProvider.secureDeployment(deploymentInfo);
+ public FilterRegistration.Dynamic secureDeployment(ServletContext servletContext) {
+ LOG.info("Securing servlet context: " + servletContext.getContextPath());
+ return identityProvider.secureDeployment(servletContext);
}
/**
@@ -73,6 +75,14 @@ public abstract class IdentityService implements ContainerService {
return identityProvider instanceof KeycloakIdentityProvider;
}
+ public TokenPrincipal verify(String realm, String accessToken) throws AuthenticationException {
+ return identityProvider.verify(realm, accessToken);
+ }
+
+ public CompletableFuture<OIDCTokenResponse> authenticate(String realm, String clientId, String clientSecret) throws AuthenticationException {
+ return identityProvider.authenticate(realm, clientId, clientSecret);
+ }
+
/**
* To configure the {@link IdentityProvider}, subclasses should override {@link #init(Container)}.
*/
diff --git a/container/src/main/java/org/openremote/container/security/JWTAuthenticationFilter.java b/container/src/main/java/org/openremote/container/security/JWTAuthenticationFilter.java
new file mode 100644
index 000000000..37f4d52d4
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/security/JWTAuthenticationFilter.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright 2026, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.container.security;
+
+import jakarta.security.enterprise.AuthenticationException;
+import jakarta.servlet.*;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequestWrapper;
+import jakarta.servlet.http.HttpServletResponse;
+import jakarta.ws.rs.NotAuthorizedException;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.HttpHeaders;
+import org.openremote.model.Constants;
+
+import java.io.IOException;
+import java.security.Principal;
+
+import static org.openremote.model.http.RequestParams.BEARER_AUTH_PREFIX;
+import static org.openremote.model.http.RequestParams.getBearerAuth;
+
+public class JWTAuthenticationFilter implements Filter {
+
+ public static final String NAME = "JWTAuthFilter";
+ public static final String AUTH_TYPE = "JWT";
+ protected final TokenVerifier tokenVerifier;
+
+ public JWTAuthenticationFilter(TokenVerifier tokenVerifier) {
+ this.tokenVerifier = tokenVerifier;
+ }
+
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
+ if (!(request instanceof HttpServletRequest httpRequest) || !(response instanceof HttpServletResponse httpResponse)) {
+ chain.doFilter(request, response);
+ return;
+ }
+
+ String realm = httpRequest.getHeader(Constants.REALM_PARAM_NAME);
+ if (realm == null) {
+ httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, Constants.REALM_PARAM_NAME + " header is missing");
+ return;
+ }
+
+ String authHeader = httpRequest.getHeader(HttpHeaders.AUTHORIZATION);
+ if (authHeader == null || !authHeader.startsWith(BEARER_AUTH_PREFIX)) {
+ // Anonymous - If the resource is protected, the container or application logic will handle the 401/403.
+ chain.doFilter(request, response);
+ return;
+ }
+
+ String token = getBearerAuth(authHeader);
+
+ try {
+ final TokenPrincipal principal = tokenVerifier.verify(realm, token);
+
+ // Wrap the request to provide security context
+ HttpServletRequestWrapper authenticatedRequest = new HttpServletRequestWrapper(httpRequest) {
+ @Override
+ public Principal getUserPrincipal() {
+ return principal;
+ }
+
+ @Override
+ public boolean isUserInRole(String role) {
+ return principal.isUserInRole(role);
+ }
+
+ @Override
+ public String getAuthType() {
+ return AUTH_TYPE;
+ }
+ };
+
+ chain.doFilter(authenticatedRequest, response);
+
+ } catch (AuthenticationException e) {
+ throw new NotAuthorizedException("Authentication has failed: " + e.getMessage(), Response.status(Response.Status.UNAUTHORIZED).build(), e);
+ }
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/security/KeyResolver.java b/container/src/main/java/org/openremote/container/security/KeyResolver.java
new file mode 100644
index 000000000..8b1cbb57d
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/security/KeyResolver.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2026, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.container.security;
+
+import com.nimbusds.jose.jwk.source.JWKSource;
+import com.nimbusds.jose.jwk.source.JWKSourceBuilder;
+import com.nimbusds.jose.proc.SecurityContext;
+
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URL;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+public class KeyResolver {
+
+ private String keycloakBaseUrl;
+ private final ConcurrentMap<String, JWKSource<SecurityContext>> jwkSources = new ConcurrentHashMap<>();
+
+ public KeyResolver(String keycloakBaseUrl) {
+ this.keycloakBaseUrl = keycloakBaseUrl;
+ }
+
+ /**
+ * Returns a JWKSource for the given Keycloak realm.
+ * The source handles caching of the JSON Web Key Set (JWKS).
+ */
+ public JWKSource<SecurityContext> getJwkSource(String realm) {
+ // computeIfAbsent ensures the source is created only once per realm in a thread-safe way.
+ return jwkSources.computeIfAbsent(realm, r -> {
+ try {
+ // The standard URL for the JWKS endpoint in Keycloak
+ URL jwksUrl = URI.create(keycloakBaseUrl + "/realms/" + r + "/protocol/openid-connect/certs").toURL();
+ return JWKSourceBuilder.create(jwksUrl).build();
+ } catch (MalformedURLException e) {
+ throw new IllegalStateException("Invalid Keycloak JWKS URL for realm: " + r, e);
+ }
+ });
+ }
+
+ public String getKeycloakBaseUrl() {
+ return keycloakBaseUrl;
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/security/OIDCTokenResponse.java b/container/src/main/java/org/openremote/container/security/OIDCTokenResponse.java
new file mode 100644
index 000000000..0b00fe447
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/security/OIDCTokenResponse.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright 2026, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.container.security;
+
+import org.keycloak.representations.AccessTokenResponse;
+
+/**
+ * Describes the payload returned by an OIDC token endpoint.
+ */
+public interface OIDCTokenResponse {
+ String getToken();
+ String getIdToken();
+ String getRefreshToken();
+ String getTokenType();
+ long getRefreshExpiresIn();
+ long getExpiresIn();
+ String getScope();
+ int getNotBeforePolicy();
+ String getSessionState();
+
+ static OIDCTokenResponse create(AccessTokenResponse keycloakTokenResponse) {
+ return new OIDCTokenResponse() {
+ @Override
+ public String getToken() {
+ return keycloakTokenResponse.getToken();
+ }
+
+ @Override
+ public String getIdToken() {
+ return keycloakTokenResponse.getIdToken();
+ }
+
+ @Override
+ public String getRefreshToken() {
+ return keycloakTokenResponse.getRefreshToken();
+ }
+
+ @Override
+ public String getTokenType() {
+ return keycloakTokenResponse.getTokenType();
+ }
+
+ @Override
+ public long getRefreshExpiresIn() {
+ return keycloakTokenResponse.getRefreshExpiresIn();
+ }
+
+ @Override
+ public long getExpiresIn() {
+ return keycloakTokenResponse.getExpiresIn();
+ }
+
+ @Override
+ public String getScope() {
+ return keycloakTokenResponse.getScope();
+ }
+
+ @Override
+ public int getNotBeforePolicy() {
+ return keycloakTokenResponse.getNotBeforePolicy();
+ }
+
+ @Override
+ public String getSessionState() {
+ return keycloakTokenResponse.getSessionState();
+ }
+ };
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/security/TokenPrincipal.java b/container/src/main/java/org/openremote/container/security/TokenPrincipal.java
new file mode 100644
index 000000000..a91eddc3c
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/security/TokenPrincipal.java
@@ -0,0 +1,157 @@
+/*
+ * Copyright 2026, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.container.security;
+
+import com.nimbusds.jwt.JWTClaimsSet;
+
+import java.security.Principal;
+import java.text.ParseException;
+import java.util.*;
+
+public class TokenPrincipal implements Principal, AuthContext {
+
+ public static final String PREFERRED_USERNAME_CLAIM = "preferred_username";
+ public static final String CLIENT_ID_CLAIM = "azp";
+ public static final String RESOURCE_ACCESS_CLAIM = "resource_access";
+ public static final String REALM_ACCESS_CLAIM = "realm_access";
+ protected final JWTClaimsSet claimsSet;
+ protected final List<String> realmRoles;
+ protected final Map<String, List<String>> resourceRoles;
+
+ @SuppressWarnings("unchecked")
+ public TokenPrincipal(JWTClaimsSet claimsSet) throws Exception {
+ this.claimsSet = claimsSet;
+ this.resourceRoles = parseResourceAccessRoles(claimsSet);
+ this.realmRoles = parseRealmRoles(claimsSet);
+ }
+
+ @Override
+ public String getName() {
+ return claimsSet.getSubject();
+ }
+
+ public JWTClaimsSet getClaims() {
+ return claimsSet;
+ }
+
+ public String getRealm() {
+ return claimsSet.getIssuer().substring(claimsSet.getIssuer().lastIndexOf('/') + 1);
+ }
+
+ public String getSubject() {
+ return claimsSet.getSubject();
+ }
+
+ public String getUsername() {
+ try {
+ return Optional.ofNullable(claimsSet.getClaimAsString(PREFERRED_USERNAME_CLAIM)).orElseGet(claimsSet::getSubject);
+ } catch (ParseException e) {
+ return null;
+ }
+ }
+
+ public String getClientId() {
+ try {
+ return claimsSet.getClaimAsString(CLIENT_ID_CLAIM);
+ } catch (ParseException e) {
+ return null;
+ }
+ }
+
+ public List<String> getRealmRoles() {
+ return realmRoles;
+ }
+
+ public List<String> getResourceRoles(String resource) {
+ return resourceRoles.get(resource);
+ }
+
+ // TODO: Decide the role lookup logic
+ public boolean isUserInRole(String role) {
+ return realmRoles.contains(role) || resourceRoles.values().stream().anyMatch(roles -> roles.contains(role));
+ }
+
+ public boolean isUserInResourceRole(String role, String resource) {
+ return resourceRoles.getOrDefault(resource, Collections.emptyList()).contains(role);
+ }
+
+ @Override
+ public String getAuthenticatedRealmName() {
+ return getRealm();
+ }
+
+ @Override
+ public String getUserId() {
+ return getSubject();
+ }
+
+ @Override
+ public boolean hasRealmRole(String role) {
+ return realmRoles.contains(role);
+ }
+
+ @Override
+ public boolean hasResourceRole(String role, String resource) {
+ return isUserInResourceRole(role, resource);
+ }
+
+ protected static Map<String, List<String>> parseResourceAccessRoles(JWTClaimsSet claimsSet) throws ParseException {
+ Map<String, Object> resourceAccess = claimsSet.getJSONObjectClaim(RESOURCE_ACCESS_CLAIM);
+ if (resourceAccess == null || resourceAccess.isEmpty()) {
+ return Collections.emptyMap();
+ }
+
+ Map<String, List<String>> out = new HashMap<>(resourceAccess.size());
+ for (Map.Entry<String, Object> e : resourceAccess.entrySet()) {
+ String resource = e.getKey();
+ Object value = e.getValue();
+
+ if (!(value instanceof Map<?, ?> resourceObj)) {
+ continue; // unexpected shape
+ }
+
+ out.put(resource, extractStringList(resourceObj.get("roles")));
+ }
+ return out;
+ }
+
+ protected static List<String> parseRealmRoles(JWTClaimsSet claimsSet) throws ParseException {
+ Map<String, Object> realmAccess = claimsSet.getJSONObjectClaim(REALM_ACCESS_CLAIM);
+ if (realmAccess == null || realmAccess.isEmpty()) {
+ // Non-keycloak fallback: allow "roles" claim if you support it elsewhere
+ List<String> rolesFallback = claimsSet.getStringListClaim("roles");
+ return rolesFallback != null ? rolesFallback : Collections.emptyList();
+ }
+ return extractStringList(realmAccess.get("roles"));
+ }
+
+ protected static List<String> extractStringList(Object rolesValue) {
+ if (!(rolesValue instanceof List<?> list) || list.isEmpty()) {
+ return Collections.emptyList();
+ }
+ List<String> out = new ArrayList<>(list.size());
+ for (Object o : list) {
+ if (o == null) continue;
+ // Be tolerant: JSON libs sometimes deliver non-String primitives
+ out.add(String.valueOf(o));
+ }
+ return out;
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/security/KeycloakDeploymentCallback.java b/container/src/main/java/org/openremote/container/security/TokenVerifier.java
similarity index 54%
rename from manager/src/main/java/org/openremote/manager/security/KeycloakDeploymentCallback.java
rename to container/src/main/java/org/openremote/container/security/TokenVerifier.java
index 3b222eed7..c86a543b0 100644
--- a/manager/src/main/java/org/openremote/manager/security/KeycloakDeploymentCallback.java
+++ b/container/src/main/java/org/openremote/container/security/TokenVerifier.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2022, OpenRemote Inc.
+ * Copyright 2026, OpenRemote Inc.
*
* See the CONTRIBUTORS.txt file in the distribution for a
* full listing of individual contributors.
@@ -17,25 +17,11 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-package org.openremote.manager.security;
+package org.openremote.container.security;
-import org.keycloak.adapters.KeycloakDeployment;
+import jakarta.security.enterprise.AuthenticationException;
-import javax.security.auth.callback.Callback;
-
-/**
- * A {@link Callback} that should return the {@link org.keycloak.adapters.KeycloakDeployment} for the specified realm
- */
-public class KeycloakDeploymentCallback implements Callback, java.io.Serializable {
-
- protected KeycloakDeployment deployment;
-
- public KeycloakDeploymentCallback setDeployment(KeycloakDeployment deployment) {
- this.deployment = deployment;
- return this;
- }
-
- public KeycloakDeployment getDeployment() {
- return deployment;
- }
+@FunctionalInterface
+public interface TokenVerifier {
+ TokenPrincipal verify(String realm, String accessToken) throws AuthenticationException;
}
diff --git a/container/src/main/java/org/openremote/container/security/TokenVerifierImpl.java b/container/src/main/java/org/openremote/container/security/TokenVerifierImpl.java
new file mode 100644
index 000000000..0fccc0f15
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/security/TokenVerifierImpl.java
@@ -0,0 +1,147 @@
+/*
+ * Copyright 2026, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.container.security;
+
+import com.nimbusds.jose.JWSAlgorithm;
+import com.nimbusds.jose.jwk.source.JWKSource;
+import com.nimbusds.jose.proc.JWSKeySelector;
+import com.nimbusds.jose.proc.JWSVerificationKeySelector;
+import com.nimbusds.jose.proc.SecurityContext;
+import com.nimbusds.jwt.JWTClaimsSet;
+import com.nimbusds.jwt.proc.BadJWTException;
+import com.nimbusds.jwt.proc.DefaultJWTClaimsVerifier;
+import com.nimbusds.jwt.proc.DefaultJWTProcessor;
+import com.nimbusds.jwt.proc.JWTClaimsSetVerifier;
+import com.nimbusds.jwt.proc.JWTProcessor;
+import jakarta.security.enterprise.AuthenticationException;
+import org.openremote.model.Constants;
+import org.openremote.model.security.User;
+import org.openremote.model.syslog.SyslogCategory;
+
+import java.text.ParseException;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.logging.Logger;
+
+public class TokenVerifierImpl implements TokenVerifier {
+ protected static final Logger LOG = SyslogCategory.getLogger(SyslogCategory.API, TokenVerifierImpl.class.getName());
+ protected final KeyResolver keyResolverService;
+ // The public URL of the keycloak server (must match the issuer in the generated tokens)
+ protected final String keycloakPublicUrl;
+ protected final Map<String, JWTProcessor<SecurityContext>> processorCache = new ConcurrentHashMap<>();
+
+ public TokenVerifierImpl(String keycloakUrl, String keycloakPublicUrl) {
+ keyResolverService = new KeyResolver(keycloakUrl);
+ this.keycloakPublicUrl = keycloakPublicUrl;
+ }
+
+ protected JWTProcessor<SecurityContext> getJwtProcessor(String realm) {
+ return processorCache.computeIfAbsent(realm, this::initialiseProcessor);
+ }
+
+ protected JWTProcessor<SecurityContext> initialiseProcessor(String realm) {
+ DefaultJWTProcessor<SecurityContext> processor = new DefaultJWTProcessor<>();
+
+ // 1. Get the JWK source for the realm from our service
+ JWKSource<SecurityContext> keySource = keyResolverService.getJwkSource(realm);
+
+ // 3. Configure the processor with a key selector for the appropriate JWS algorithm (e.g., RS256)
+ // The key selector will use the JWK source to find the right public key by 'kid'
+ JWSKeySelector<SecurityContext> keySelector = new JWSVerificationKeySelector<>(JWSAlgorithm.RS256, keySource);
+ processor.setJWSKeySelector(keySelector);
+
+ final String expectedIssuer = keycloakPublicUrl + "/realms/" + realm;
+ final String expectedClientId = Constants.KEYCLOAK_CLIENT_ID;
+ final JWTClaimsSetVerifier<SecurityContext> defaultClaimsVerifier = new DefaultJWTClaimsVerifier<>(null, null);
+
+ JWTClaimsSetVerifier<SecurityContext> verifier = (claims, context) -> {
+ // Preserve Nimbus built-in checks for exp / nbf validation.
+ defaultClaimsVerifier.verify(claims, context);
+
+ // 1) issuer check (keep/remove depending on your policy)
+ if (claims.getIssuer() == null || !expectedIssuer.equals(claims.getIssuer())) {
+ throw new BadJWTException("Invalid token issuer");
+ }
+
+ // Keycloak uses azp to store client ID by default but we support aud for non keycloak auth servers
+ String azp = null;
+ try {
+ azp = claims.getStringClaim("azp");
+ } catch (ParseException ignored) {}
+
+ if (azp != null && !azp.isBlank()) {
+ if (expectedClientId.equals(azp)) {
+ return;
+ }
+ }
+
+ // Fall back to aud - service users put the client in the aud claim not the azp claim
+ if (claims.getAudience() == null || !claims.getAudience().contains(expectedClientId)) {
+ // TODO: Remove this once https://github.com/openremote/openremote/issues/2642 is implemented
+ try {
+ String preferredUsername = claims.getStringClaim("preferred_username");
+ if (preferredUsername == null || !preferredUsername.startsWith(User.SERVICE_ACCOUNT_PREFIX)) {
+ throw new BadJWTException("Invalid token audience");
+ }
+ } catch (ParseException ignored) {}
+ }
+ };
+
+ processor.setJWTClaimsSetVerifier(verifier);
+ return processor;
+ }
+
+ @Override
+ public TokenPrincipal verify(String realm, String token) throws AuthenticationException {
+
+ if (realm == null || realm.isBlank()) {
+ throw new AuthenticationException("Invalid token");
+ }
+ if (token == null || token.isBlank()) {
+ throw new AuthenticationException("Invalid token");
+ }
+
+ JWTProcessor<SecurityContext> jwtProcessor = getJwtProcessor(realm);
+ JWTClaimsSet claimsSet;
+ TokenPrincipal principal;
+
+ // Process the token. This verifies the signature and validates the claims
+ // We also perform super user cross realm checks
+ try {
+ claimsSet = jwtProcessor.process(token, null);
+ principal = new TokenPrincipal(claimsSet);
+
+ // Only allow super users to cross realms
+ String authRealm = principal.getRealm();
+ if (!Objects.equals(authRealm, realm)) {
+ if (!principal.hasRealmRole(Constants.SUPER_USER_REALM_ROLE)) {
+ throw new AuthenticationException("Invalid token realm");
+ }
+ }
+ } catch (Exception e) {
+ String msg = "Invalid token: " + e.getMessage();
+ LOG.info(msg);
+ throw new AuthenticationException(msg);
+ }
+
+ return principal;
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/security/WebsocketAuthParamHandler.java b/container/src/main/java/org/openremote/container/security/WebsocketAuthParamHandler.java
deleted file mode 100644
index 7bbbf90c7..000000000
--- a/container/src/main/java/org/openremote/container/security/WebsocketAuthParamHandler.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright 2016, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.container.security;
-
-import io.undertow.server.HttpHandler;
-import io.undertow.server.HttpServerExchange;
-import io.undertow.util.HttpString;
-
-import java.util.Deque;
-
-import static jakarta.ws.rs.core.HttpHeaders.AUTHORIZATION;
-import static org.openremote.model.Constants.REALM_PARAM_NAME;
-
-/**
- * For use by websocket requests where Authorization header cannot be set; grabs the
- * {@link jakarta.ws.rs.core.HttpHeaders#AUTHORIZATION} query parameter and sets it as a regular header. This handler
- * will also grab {@link org.openremote.model.Constants#REALM_PARAM_NAME} as a request parameter and set it as a regular
- * header.
- */
-public class WebsocketAuthParamHandler implements HttpHandler {
-
- final protected HttpHandler next;
-
- public WebsocketAuthParamHandler(HttpHandler next) {
- this.next = next;
- }
-
- @Override
- public void handleRequest(HttpServerExchange exchange) throws Exception {
- Deque<String> authParameter = exchange.getQueryParameters().get(AUTHORIZATION);
- if (authParameter != null && authParameter.peekFirst() != null) {
- exchange.getRequestHeaders().put(HttpString.tryFromString(AUTHORIZATION), authParameter.pollFirst());
- }
-
- Deque<String> authRealmParameter = exchange.getQueryParameters().get(REALM_PARAM_NAME);
- if (authRealmParameter != null && authRealmParameter.peekFirst() != null) {
- exchange.getRequestHeaders().put(HttpString.tryFromString(REALM_PARAM_NAME), authRealmParameter.pollFirst());
- }
-
- next.handleRequest(exchange);
- }
-}
diff --git a/container/src/main/java/org/openremote/container/security/basic/BasicIdentityProvider.java b/container/src/main/java/org/openremote/container/security/basic/BasicIdentityProvider.java
index 07bc1063d..8521e4e81 100644
--- a/container/src/main/java/org/openremote/container/security/basic/BasicIdentityProvider.java
+++ b/container/src/main/java/org/openremote/container/security/basic/BasicIdentityProvider.java
@@ -19,111 +19,30 @@
*/
package org.openremote.container.security.basic;
-import io.undertow.UndertowMessages;
-import io.undertow.security.api.AuthenticationMechanism;
-import io.undertow.security.api.AuthenticationMechanismFactory;
-import io.undertow.security.api.SecurityContext;
import io.undertow.security.idm.Account;
-import io.undertow.security.idm.Credential;
-import io.undertow.security.idm.IdentityManager;
-import io.undertow.security.idm.PasswordCredential;
-import io.undertow.security.impl.BasicAuthenticationMechanism;
-import io.undertow.server.HttpServerExchange;
-import io.undertow.server.handlers.form.FormParserFactory;
-import io.undertow.servlet.api.AuthMethodConfig;
-import io.undertow.servlet.api.DeploymentInfo;
-import io.undertow.servlet.api.LoginConfig;
-import org.openremote.model.Container;
+import jakarta.persistence.NoResultException;
+import jakarta.persistence.NonUniqueResultException;
+import jakarta.security.enterprise.AuthenticationException;
+import jakarta.servlet.FilterRegistration;
+import jakarta.servlet.ServletContext;
import org.openremote.container.persistence.PersistenceService;
import org.openremote.container.security.IdentityProvider;
+import org.openremote.container.security.OIDCTokenResponse;
+import org.openremote.container.security.TokenPrincipal;
import org.openremote.model.Constants;
+import org.openremote.model.Container;
-import jakarta.persistence.NoResultException;
-import jakarta.persistence.NonUniqueResultException;
-import java.nio.charset.Charset;
-import java.nio.charset.StandardCharsets;
import java.security.Principal;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
import java.util.Set;
+import java.util.concurrent.CompletableFuture;
import java.util.logging.Logger;
-import java.util.regex.Pattern;
-
-import static io.undertow.util.Headers.AUTHORIZATION;
+@Deprecated
+/**
+ * This identity provider is scheduled to be removed
+ */
public abstract class BasicIdentityProvider implements IdentityProvider {
- /**
- * This is a fix for {@link BasicAuthenticationMechanism} which doesn't conform to RFC2617.
- * see: https://issues.redhat.com/browse/UNDERTOW-1727
- * <p>
- * When no {@link io.undertow.util.Headers#AUTHORIZATION} header is supplied then a 401 is returned with
- * {@link io.undertow.util.Headers#WWW_AUTHENTICATE} header unless {@link #silent} is true in which case
- * a 403 will be returned.
- * <p>
- * When an {@link io.undertow.util.Headers#AUTHORIZATION} header is supplied and is valid then the request
- * can proceed otherwise a 403 is returned.
- */
- protected static class BasicFixAuthenticationMechanism extends BasicAuthenticationMechanism {
-
- protected static class Factory implements AuthenticationMechanismFactory {
- @Override
- public AuthenticationMechanism create(String mechanismName, IdentityManager identityManager, FormParserFactory formParserFactory, Map<String, String> properties) {
- String realm = properties.get(REALM);
- String silent = properties.get(SILENT);
- String charsetString = properties.get(CHARSET);
- Charset charset = charsetString == null ? StandardCharsets.UTF_8 : Charset.forName(charsetString);
- Map<Pattern, Charset> userAgentCharsets = new HashMap<>();
- String userAgentString = properties.get(USER_AGENT_CHARSETS);
- if(userAgentString != null) {
- String[] parts = userAgentString.split(",");
- if(parts.length % 2 != 0) {
- throw UndertowMessages.MESSAGES.userAgentCharsetMustHaveEvenNumberOfItems(userAgentString);
- }
- for(int i = 0; i < parts.length; i += 2) {
- Pattern pattern = Pattern.compile(parts[i]);
- Charset c = Charset.forName(parts[i + 1]);
- userAgentCharsets.put(pattern, c);
- }
- }
- return new BasicFixAuthenticationMechanism(realm, mechanismName, silent != null && silent.equals("true"), identityManager, charset, userAgentCharsets);
- }
- }
-
- // field is private in super class so need to redefine!!!
- private final boolean silent;
- public static Factory FACTORY = new Factory();
-
- public BasicFixAuthenticationMechanism(String realmName, String mechanismName, boolean silent, IdentityManager identityManager, Charset charset, Map<Pattern, Charset> userAgentCharsets) {
- super(realmName, mechanismName, false, identityManager, charset, userAgentCharsets);
- this.silent = silent;
- }
-
- @Override
- public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
- String authHeader = exchange.getRequestHeaders().getFirst(AUTHORIZATION);
-
- if (authHeader == null) {
- if (silent) {
- return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
- } else {
- return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
- }
- }
- return super.authenticate(exchange, securityContext);
- }
-
- @Override
- public ChallengeResult sendChallenge(HttpServerExchange exchange, SecurityContext securityContext) {
- String authHeader = exchange.getRequestHeaders().getFirst(AUTHORIZATION);
- if (silent || authHeader != null) {
- return ChallengeResult.NOT_SENT;
- }
- return super.sendChallenge(exchange, securityContext);
- }
- }
-
private static final Logger LOG = Logger.getLogger(BasicIdentityProvider.class.getName());
protected PersistenceService persistenceService;
@@ -148,34 +67,8 @@ public abstract class BasicIdentityProvider implements IdentityProvider {
}
@Override
- public void secureDeployment(DeploymentInfo deploymentInfo) {
- LoginConfig loginConfig = new LoginConfig("OpenRemote");
- // Make it silent to prevent 401 WWW-Authenticate modal dialog
- deploymentInfo.addAuthenticationMechanism("BASIC-FIX", BasicFixAuthenticationMechanism.FACTORY);
- loginConfig.addFirstAuthMethod(new AuthMethodConfig("BASIC-FIX", Collections.singletonMap("silent", "true")));
- deploymentInfo.setLoginConfig(loginConfig);
- deploymentInfo.setIdentityManager(new IdentityManager() {
- @Override
- public Account verify(Account account) {
- return null;
- }
-
- @Override
- public Account verify(String id, Credential credential) {
- if (credential instanceof PasswordCredential) {
- PasswordCredential passwordCredential = (PasswordCredential) credential;
- return verifyAccount(id, passwordCredential.getPassword());
- } else {
- LOG.fine("Verification of '" + id + "' failed, no password credentials found, but: " + credential);
- return null;
- }
- }
-
- @Override
- public Account verify(Credential credential) {
- return null;
- }
- });
+ public FilterRegistration.Dynamic secureDeployment(ServletContext servletContext) {
+ throw new UnsupportedOperationException("Basic authentication is not supported for servlet deployments");
}
protected Account verifyAccount(String username, char[] password) {
@@ -216,4 +109,14 @@ public abstract class BasicIdentityProvider implements IdentityProvider {
}
abstract protected Set<String> getDefaultRoles();
+
+ @Override
+ public TokenPrincipal verify(String realm, String accessToken) throws AuthenticationException {
+ return null;
+ }
+
+ @Override
+ public CompletableFuture<OIDCTokenResponse> authenticate(String realm, String clientId, String clientSecret) {
+ return CompletableFuture.failedFuture(new AuthenticationException("This provider does not support bearer tokens"));
+ }
}
diff --git a/container/src/main/java/org/openremote/container/security/keycloak/AccessTokenAuthContext.java b/container/src/main/java/org/openremote/container/security/keycloak/AccessTokenAuthContext.java
deleted file mode 100644
index bc6621250..000000000
--- a/container/src/main/java/org/openremote/container/security/keycloak/AccessTokenAuthContext.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright 2017, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.container.security.keycloak;
-
-import org.keycloak.representations.AccessToken;
-import org.openremote.container.security.AuthContext;
-
-/**
- * Keycloak-based authorization.
- */
-public class AccessTokenAuthContext implements AuthContext {
-
- final protected String authenticatedRealm;
- final protected AccessToken accessToken;
-
- public AccessTokenAuthContext(String authenticatedRealm, AccessToken accessToken) {
- this.authenticatedRealm = authenticatedRealm;
- this.accessToken = accessToken;
- }
-
- @Override
- public String getAuthenticatedRealmName() {
- return authenticatedRealm;
- }
-
- @Override
- public String getUsername() {
- return accessToken.getPreferredUsername();
- }
-
- @Override
- public String getUserId() {
- return accessToken.getSubject();
- }
-
- @Override
- public String getClientId() {
- return accessToken.getIssuedFor();
- }
-
- @Override
- public boolean hasRealmRole(String role) {
- return accessToken.getRealmAccess() != null && accessToken.getRealmAccess().isUserInRole(role);
- }
-
- @Override
- public boolean hasResourceRole(String role, String resource) {
- return accessToken.getResourceAccess().containsKey(resource)
- && accessToken.getResourceAccess().get(resource).isUserInRole(role);
- }
-}
diff --git a/container/src/main/java/org/openremote/container/security/keycloak/KeycloakIdentityProvider.java b/container/src/main/java/org/openremote/container/security/keycloak/KeycloakIdentityProvider.java
index 29d34f02e..d48f57f63 100644
--- a/container/src/main/java/org/openremote/container/security/keycloak/KeycloakIdentityProvider.java
+++ b/container/src/main/java/org/openremote/container/security/keycloak/KeycloakIdentityProvider.java
@@ -19,32 +19,28 @@
*/
package org.openremote.container.security.keycloak;
-import com.google.common.cache.CacheBuilder;
-import com.google.common.cache.CacheLoader;
-import com.google.common.cache.LoadingCache;
import io.undertow.server.HttpHandler;
import io.undertow.server.handlers.ResponseCodeHandler;
import io.undertow.server.handlers.proxy.LoadBalancingProxyClient;
import io.undertow.server.handlers.proxy.ProxyHandler;
-import io.undertow.servlet.api.DeploymentInfo;
-import io.undertow.servlet.api.LoginConfig;
-import jakarta.ws.rs.NotFoundException;
+import jakarta.security.enterprise.AuthenticationException;
+import jakarta.servlet.FilterRegistration;
+import jakarta.servlet.ServletContext;
+import jakarta.ws.rs.WebApplicationException;
+import jakarta.ws.rs.client.WebTarget;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriBuilder;
-import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.keycloak.KeycloakPrincipal;
import org.keycloak.KeycloakSecurityContext;
-import org.keycloak.adapters.KeycloakConfigResolver;
-import org.keycloak.adapters.KeycloakDeployment;
-import org.keycloak.adapters.KeycloakDeploymentBuilder;
import org.keycloak.admin.client.resource.RealmsResource;
-import org.keycloak.representations.AccessToken;
-import org.keycloak.representations.adapters.config.AdapterConfig;
-import org.openremote.container.security.IdentityProvider;
+import org.openremote.container.security.*;
import org.openremote.container.web.WebService;
import org.openremote.container.web.WebTargetBuilder;
import org.openremote.model.Constants;
import org.openremote.model.Container;
+import org.openremote.model.auth.OAuthClientCredentialsGrant;
import org.openremote.model.auth.OAuthGrant;
import org.openremote.model.auth.OAuthPasswordGrant;
import org.openremote.model.util.TextUtil;
@@ -52,22 +48,28 @@ import org.openremote.model.util.TextUtil;
import javax.security.auth.Subject;
import java.net.URI;
import java.security.Principal;
-import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.Function;
-import java.util.logging.Level;
import java.util.logging.Logger;
+import static org.openremote.model.Constants.MASTER_REALM;
+import static org.openremote.model.Constants.MASTER_REALM_ADMIN_USER;
import static org.openremote.model.Constants.*;
import static org.openremote.model.util.MapAccess.getInteger;
import static org.openremote.model.util.MapAccess.getString;
public abstract class KeycloakIdentityProvider implements IdentityProvider {
+ public record DiscoveryResult (
+ String issuer
+ ) {}
+
// We use this client ID to access Keycloak because by default it allows obtaining
// an access token from authentication directly, which gives us full access to import/delete
// demo data as needed.
@@ -81,11 +83,12 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
"security-admin-console");
public static final String OR_KEYCLOAK_HOST = "OR_KEYCLOAK_HOST";
- public static final String OR_KEYCLOAK_HOST_DEFAULT = "127.0.0.1"; // Bug in keycloak default hostname provider means localhost causes problems with dev-proxy profile
+ public static final String OR_KEYCLOAK_HOST_DEFAULT = "localhost";
public static final String OR_KEYCLOAK_PORT = "OR_KEYCLOAK_PORT";
public static final int OR_KEYCLOAK_PORT_DEFAULT = 8081;
public static final String OR_KEYCLOAK_PATH = "OR_KEYCLOAK_PATH";
public static final String OR_KEYCLOAK_PATH_DEFAULT = "/auth";
+ public static final String OIDC_CONFIG_PATH = "/realms/master/.well-known/openid-configuration";
public static final String KEYCLOAK_REQUEST_TIMEOUT = "KEYCLOAK_REQUEST_TIMEOUT";
public static final int KEYCLOAK_REQUEST_TIMEOUT_DEFAULT = 10000;
public static final String OR_IDENTITY_SESSION_MAX_MINUTES = "OR_IDENTITY_SESSION_MAX_MINUTES";
@@ -99,17 +102,12 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
protected int sessionTimeoutSeconds;
protected int sessionMaxSeconds;
protected int sessionOfflineTimeoutSeconds;
- // This will pass authentication ("NOT ATTEMPTED" state), but later fail any role authorization
- final protected KeycloakDeployment notAuthenticatedKeycloakDeployment = new KeycloakDeployment();
protected ResteasyWebTarget keycloakTarget;
protected OAuthGrant oAuthGrant;
protected ConcurrentLinkedQueue<RealmsResource> realmsResourcePool = new ConcurrentLinkedQueue<>();
- // Cache Keycloak deployment per realm/client so we don't have to access Keycloak for every token validation
- protected LoadingCache<KeycloakRealmClient, KeycloakDeployment> keycloakDeploymentCache;
- // The configuration for the Keycloak servlet extension, looks up the openremote client application per realm
- protected KeycloakConfigResolver keycloakConfigResolver;
// Optional reverse proxy that listens to KEYCLOAK_AUTH_PATH and forwards requests to Keycloak (used in dev mode to allow same url to be used for manager and keycloak) - handled by proxy in production
protected HttpHandler authProxyHandler;
+ protected TokenVerifier tokenVerifier;
/**
* The supplied {@link OAuthGrant} will be used to authenticate with keycloak so we can programmatically make changes.
@@ -159,23 +157,6 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
LOG.info("Keycloak service URL: " + keycloakServiceUri.build());
- keycloakDeploymentCache = createKeycloakDeploymentCache();
-
- keycloakConfigResolver = request -> {
- // The realm we authenticate against must be available as a request header
- String realm = request.getHeader(REALM_PARAM_NAME);
- if (realm == null || realm.isEmpty()) {
- LOG.finest("No realm in request, no authentication will be attempted: " + request.getURI());
- return notAuthenticatedKeycloakDeployment;
- }
- KeycloakDeployment keycloakDeployment = getKeycloakDeployment(realm, KEYCLOAK_CLIENT_ID);
- if (keycloakDeployment == null) {
- LOG.fine("No Keycloak deployment available for realm, no authentication will be attempted: " + request.getURI());
- return notAuthenticatedKeycloakDeployment;
- }
- return keycloakDeployment;
- };
-
if (container.isDevMode()) {
authProxyHandler = ProxyHandler.builder()
.setProxyClient(new LoadBalancingProxyClient().addHost(keycloakServiceUri.build()))
@@ -184,6 +165,12 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
.setReuseXForwarded(true)
.build();
}
+
+ // Get public URL of keycloak from the keycloak server
+ String keycloakPublicUrl = getKeycloakPublicUrl();
+ tokenVerifier = new TokenVerifierImpl(
+ keycloakServiceUri.build().toString(),
+ keycloakPublicUrl != null ? keycloakPublicUrl : keycloakServiceUri.build().toString());
}
@Override
@@ -231,14 +218,14 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
}
@Override
- public void secureDeployment(DeploymentInfo deploymentInfo) {
- LoginConfig loginConfig = new LoginConfig(SimpleKeycloakServletExtension.AUTH_MECHANISM, "OpenRemote");
- deploymentInfo.setLoginConfig(loginConfig);
- deploymentInfo.addServletExtension(new SimpleKeycloakServletExtension(keycloakConfigResolver));
+ public FilterRegistration.Dynamic secureDeployment(ServletContext servletContext) {
+ JWTAuthenticationFilter jwtFilter = new JWTAuthenticationFilter(tokenVerifier);
+ FilterRegistration.Dynamic registration = servletContext.addFilter(JWTAuthenticationFilter.NAME, jwtFilter);
+ return registration;
}
- public KeycloakResource getKeycloak() {
- return keycloakTarget.proxy(KeycloakResource.class);
+ protected ReactiveTokenService getReactiveTokenService() {
+ return keycloakTarget.proxy(ReactiveTokenService.class);
}
//There is a bug in {@link org.keycloak.admin.client.resource.UserStorageProviderResource#syncUsers} which misses the componentId as parameter
@@ -264,28 +251,7 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
}
}
- public synchronized KeycloakDeployment getKeycloakDeployment(String realm, String clientId) {
- if (realm == null || clientId == null) {
- return null;
- }
- try {
- return keycloakDeploymentCache.get(new KeycloakRealmClient(realm, clientId));
- } catch (Exception ex) {
- if (ex.getCause() != null && ex.getCause() instanceof NotFoundException) {
- LOG.fine("Client '" + clientId + "' for realm '" + realm + "' not found on identity provider");
- } else {
- LOG.log(
- Level.WARNING,
- "Error loading client '" + clientId + "' for realm '" + realm + "' from identity provider, " +
- "exception from call to identity provider follows",
- ex
- );
- }
- return null;
- }
- }
-
- public URI getTokenUri(String realm) {
+ protected URI getTokenUri(String realm) {
return keycloakServiceUri.clone().path("realms").path(realm).path("protocol/openid-connect/token").build();
}
@@ -339,39 +305,6 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
*/
protected abstract OAuthGrant generateStoredCredentials(Container container);
- protected LoadingCache<KeycloakRealmClient, KeycloakDeployment> createKeycloakDeploymentCache() {
- CacheLoader<KeycloakRealmClient, KeycloakDeployment> loader =
- new CacheLoader<KeycloakRealmClient, KeycloakDeployment>() {
- public KeycloakDeployment load(KeycloakRealmClient keycloakRealmClient) {
- LOG.finest("Loading adapter config for client '" + keycloakRealmClient.clientId + "' in realm '" + keycloakRealmClient.realm + "'");
-
- //KeycloakResource keycloak = getKeycloak();
- KeycloakResource keycloak = new WebTargetBuilder(WebTargetBuilder.getClient(), keycloakServiceUri.build()).build().proxy(KeycloakResource.class);
-
- // Can't get adapter for client in another realm
- AdapterConfig adapterConfig = keycloak.getAdapterConfig(
- keycloakRealmClient.realm, KEYCLOAK_CLIENT_ID//keycloakRealmClient.clientId
- );
-
- // The auth-server-url in the adapter config must be reachable by this manager it will be the frontend URL by default
- adapterConfig.setAuthServerUrl(
- keycloakServiceUri.clone().build().toString()
- );
-
- // Set preferred username as principal attribute
- adapterConfig.setPrincipalAttribute("preferred_username");
-
- return KeycloakDeploymentBuilder.build(adapterConfig);
- }
- };
-
- // TODO configurable? Or replace all of this with Observable.cache()?
- return CacheBuilder.newBuilder()
- .maximumSize(500)
- .expireAfterWrite(Duration.ofMinutes(10))
- .build(loader);
- }
-
protected void enableAuthProxy(WebService webService, String keycloakPath) {
if (authProxyHandler == null)
throw new IllegalStateException("Initialize this service first");
@@ -385,16 +318,6 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
*/
abstract protected void addClientRedirectUris(String client, List<String> redirectUrls, boolean devMode);
- public static KeycloakSecurityContext getSecurityContext(Subject subject) {
- if (subject == null || subject.getPrincipals() == null) {
- return null;
- }
-
- return subject.getPrincipals().stream().filter(p -> p instanceof KeycloakPrincipal<?>).findFirst()
- .map(keycloakPrincipal ->
- ((KeycloakPrincipal<?>)keycloakPrincipal).getKeycloakSecurityContext()).orElse(null);
- }
-
public static String getSubjectName(Subject subject) {
if (subject == null || subject.getPrincipals() == null) {
return null;
@@ -404,10 +327,6 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
.map(Principal::getName).orElse(null);
}
- public static String getSubjectName(Principal principal) {
- return Optional.ofNullable(principal).map(Principal::getName).orElse(null);
- }
-
public static String getSubjectNameAndRealm(Principal principal) {
return Optional.ofNullable(principal).map(p -> {
if (p instanceof KeycloakPrincipal<?>) {
@@ -431,18 +350,63 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
}).orElse(null);
}
- public static String getSubjectId(Subject subject) {
- if (subject == null || subject.getPrincipals() == null) {
- return null;
- }
+ public static boolean isSuperUser(KeycloakSecurityContext securityContext) {
+ return securityContext != null && Constants.MASTER_REALM.equals(securityContext.getRealm()) && securityContext.getToken().getRealmAccess().isUserInRole(Constants.SUPER_USER_REALM_ROLE);
+ }
- return Optional.ofNullable(getSecurityContext(subject))
- .map(KeycloakSecurityContext::getToken)
- .map(AccessToken::getSubject)
- .orElse(null);
+ @Override
+ public CompletableFuture<OIDCTokenResponse> authenticate(String realm, String clientId, String clientSecret) {
+ return getReactiveTokenService().grantToken(
+ realm,
+ new OAuthClientCredentialsGrant(null, clientId, clientSecret, null).asMultivaluedMap())
+ .toCompletableFuture()
+ .exceptionallyCompose(ex -> {
+ Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
+
+ if (cause instanceof WebApplicationException webEx) {
+ if (webEx.getResponse() != null) {
+ // Ensure the response is closed to free the connection
+ webEx.getResponse().close();
+ }
+ }
+
+ if (!(cause instanceof AuthenticationException)) {
+ return CompletableFuture.failedFuture(new AuthenticationException(cause));
+ }
+
+ return CompletableFuture.failedFuture(cause);
+ })
+ .thenApply(OIDCTokenResponse::create)
+ .toCompletableFuture();
}
- public static boolean isSuperUser(KeycloakSecurityContext securityContext) {
- return securityContext != null && Constants.MASTER_REALM.equals(securityContext.getRealm()) && securityContext.getToken().getRealmAccess().isUserInRole(Constants.SUPER_USER_REALM_ROLE);
+ @Override
+ public TokenPrincipal verify(String realm, String accessToken) throws AuthenticationException {
+ return tokenVerifier.verify(realm, accessToken);
+ }
+
+ protected String getKeycloakPublicUrl() {
+ WebTarget webTarget = new WebTargetBuilder(
+ WebTargetBuilder.getClient(),
+ keycloakServiceUri.build()).build().path(OIDC_CONFIG_PATH);
+
+ LOG.info("Getting public URL of keycloak from the keycloak OIDC discovery endpoint: " + webTarget.getUri());
+ DiscoveryResult result = null;
+ try (Response response = webTarget.request(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON_TYPE).get()) {
+
+ if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
+ String body = "<unreadable>";
+ try {
+ body = response.readEntity(String.class);
+ } catch (Exception ignore) {}
+
+ LOG.severe("OIDC discovery failed: HTTP " + response.getStatus() + " body=" + body);
+ } else {
+ result = response.readEntity(DiscoveryResult.class);
+ }
+ }
+
+ // We want the base public URI not the master specific one
+ return result != null ? result.issuer().replace("/realms/master", "") : keycloakServiceUri.build().toString();
}
}
diff --git a/container/src/main/java/org/openremote/container/security/keycloak/KeycloakRealmClient.java b/container/src/main/java/org/openremote/container/security/keycloak/KeycloakRealmClient.java
deleted file mode 100644
index 4caa8a4a5..000000000
--- a/container/src/main/java/org/openremote/container/security/keycloak/KeycloakRealmClient.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright 2016, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.container.security.keycloak;
-
-public class KeycloakRealmClient {
-
- public final String realm;
- public final String clientId;
-
- public KeycloakRealmClient(String realm, String clientId) {
- this.realm = realm;
- this.clientId = clientId;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- KeycloakRealmClient that = (KeycloakRealmClient) o;
-
- if (!realm.equals(that.realm)) return false;
- return clientId.equals(that.clientId);
-
- }
-
- @Override
- public int hashCode() {
- int result = realm.hashCode();
- result = 31 * result + clientId.hashCode();
- return result;
- }
-
-}
diff --git a/container/src/main/java/org/openremote/container/security/keycloak/KeycloakResource.java b/container/src/main/java/org/openremote/container/security/keycloak/KeycloakResource.java
deleted file mode 100644
index 96d415d1b..000000000
--- a/container/src/main/java/org/openremote/container/security/keycloak/KeycloakResource.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright 2016, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.container.security.keycloak;
-
-import org.keycloak.representations.AccessTokenResponse;
-import org.keycloak.representations.adapters.config.AdapterConfig;
-import org.keycloak.representations.idm.PublishedRealmRepresentation;
-import org.openremote.container.security.PasswordAuthForm;
-import org.openremote.container.security.ClientCredentialsAuthForm;
-
-import jakarta.ws.rs.*;
-import jakarta.ws.rs.core.Response;
-
-import static jakarta.ws.rs.core.MediaType.*;
-
-public interface KeycloakResource {
-
- @GET
- @Path("/")
- @Produces(TEXT_HTML)
- Response getWelcomePage();
-
- @POST
- @Path("realms/{realm}/protocol/openid-connect/token")
- @Consumes(APPLICATION_FORM_URLENCODED)
- @Produces(APPLICATION_JSON)
- AccessTokenResponse getAccessToken(@PathParam("realm") String realm, @BeanParam PasswordAuthForm authForm);
-
- @POST
- @Path("realms/{realm}/protocol/openid-connect/token")
- @Consumes(APPLICATION_FORM_URLENCODED)
- @Produces(APPLICATION_JSON)
- AccessTokenResponse getAccessToken(@PathParam("realm") String realm, @BeanParam ClientCredentialsAuthForm authForm);
-
- @GET
- @Path("realms/{realm}")
- @Produces(APPLICATION_JSON)
- PublishedRealmRepresentation getPublishedRealm(@PathParam("realm") String realm);
-
- @GET
- @Path("realms/{realm}/clients-registrations/install/{clientId}")
- @Produces(APPLICATION_JSON)
- AdapterConfig getAdapterConfig(@PathParam("realm") String realm, @PathParam("clientId") String clientId);
-
-}
diff --git a/container/src/main/java/org/openremote/container/security/keycloak/ReactiveTokenService.java b/container/src/main/java/org/openremote/container/security/keycloak/ReactiveTokenService.java
new file mode 100644
index 000000000..367469d3f
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/security/keycloak/ReactiveTokenService.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2026, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.container.security.keycloak;
+
+import jakarta.ws.rs.*;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.MultivaluedMap;
+import org.keycloak.representations.AccessTokenResponse;
+
+import java.util.concurrent.CompletionStage;
+
+/**
+ * This is a reactive async version of the keycloak {@link org.keycloak.admin.client.token.TokenService}
+ */
+@Produces(MediaType.APPLICATION_JSON)
+@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
+public interface ReactiveTokenService {
+
+ @POST
+ @Path("/realms/{realm}/protocol/openid-connect/token")
+ CompletionStage<AccessTokenResponse> grantToken(@PathParam("realm") String realm, MultivaluedMap<String, String> map);
+
+ @POST
+ @Path("/realms/{realm}/protocol/openid-connect/token")
+ CompletionStage<AccessTokenResponse> refreshToken(@PathParam("realm") String realm, MultivaluedMap<String, String> map);
+
+ @POST
+ @Path("/realms/{realm}/protocol/openid-connect/logout")
+ CompletionStage<Void> logout(@PathParam("realm") String realm, MultivaluedMap<String, String> map);
+}
diff --git a/container/src/main/java/org/openremote/container/security/keycloak/SimpleKeycloakServletExtension.java b/container/src/main/java/org/openremote/container/security/keycloak/SimpleKeycloakServletExtension.java
deleted file mode 100644
index f0adc3462..000000000
--- a/container/src/main/java/org/openremote/container/security/keycloak/SimpleKeycloakServletExtension.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed 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.openremote.container.security.keycloak;
-
-import io.undertow.security.api.AuthenticationMechanism;
-import io.undertow.security.api.AuthenticationMechanismFactory;
-import io.undertow.security.idm.Account;
-import io.undertow.security.idm.Credential;
-import io.undertow.security.idm.IdentityManager;
-import io.undertow.server.handlers.form.FormParserFactory;
-import io.undertow.servlet.ServletExtension;
-import io.undertow.servlet.api.*;
-import io.undertow.servlet.util.ImmediateInstanceHandle;
-import org.jboss.logging.Logger;
-import org.keycloak.adapters.AdapterDeploymentContext;
-import org.keycloak.adapters.KeycloakConfigResolver;
-import org.keycloak.adapters.NodesRegistrationManagement;
-import org.keycloak.adapters.undertow.*;
-
-import jakarta.servlet.ServletContext;
-import java.util.Map;
-
-/**
- * Allow Java setup of config resolver. We don't want your stupid text files and properties.
- *
- * @author <a href="mailto:[email protected]">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class SimpleKeycloakServletExtension implements ServletExtension {
-
- public static final String AUTH_MECHANISM = "SIMPLE_KEYCLOAK";
-
- protected static Logger log = Logger.getLogger(SimpleKeycloakServletExtension.class);
-
- final protected KeycloakConfigResolver configResolver;
- final protected AdapterDeploymentContext deploymentContext;
-
- public SimpleKeycloakServletExtension(KeycloakConfigResolver configResolver) {
- this.configResolver = configResolver;
- deploymentContext = new AdapterDeploymentContext(configResolver);
- }
-
- @Override
- @SuppressWarnings("UseSpecificCatch")
- public void handleDeployment(DeploymentInfo deploymentInfo, ServletContext servletContext) {
-
- servletContext.setAttribute(AdapterDeploymentContext.class.getName(), deploymentContext);
- UndertowUserSessionManagement userSessionManagement = new UndertowUserSessionManagement();
- final NodesRegistrationManagement nodesRegistrationManagement = new NodesRegistrationManagement();
- final ServletKeycloakAuthMech mech = createAuthenticationMechanism(deploymentInfo, deploymentContext, userSessionManagement, nodesRegistrationManagement);
-
- UndertowAuthenticatedActionsHandler.Wrapper actions = new UndertowAuthenticatedActionsHandler.Wrapper(deploymentContext);
-
- // setup handlers
-
- deploymentInfo.addOuterHandlerChainWrapper(new ServletPreAuthActionsHandler.Wrapper(deploymentContext, userSessionManagement));
- deploymentInfo.addAuthenticationMechanism(AUTH_MECHANISM, new AuthenticationMechanismFactory() {
- @Override
- public AuthenticationMechanism create(String s, IdentityManager identityManager, FormParserFactory formParserFactory, Map<String, String> stringStringMap) {
- return mech;
- }
- }); // authentication
- deploymentInfo.addInnerHandlerChainWrapper(actions); // handles authenticated actions and cors.
-
- deploymentInfo.setIdentityManager(new IdentityManager() {
- @Override
- public Account verify(Account account) {
- return account;
- }
-
- @Override
- public Account verify(String id, Credential credential) {
- throw new IllegalStateException("Should never be called in Keycloak flow");
- }
-
- @Override
- public Account verify(Credential credential) {
- throw new IllegalStateException("Should never be called in Keycloak flow");
- }
- });
-
- ServletSessionConfig cookieConfig = deploymentInfo.getServletSessionConfig();
- if (cookieConfig == null) {
- cookieConfig = new ServletSessionConfig();
- }
- if (cookieConfig.getPath() == null) {
- log.debug("Setting jsession cookie path to: " + deploymentInfo.getContextPath());
- cookieConfig.setPath(deploymentInfo.getContextPath());
- deploymentInfo.setServletSessionConfig(cookieConfig);
- }
- ChangeSessionId.turnOffChangeSessionIdOnLogin(deploymentInfo);
-
- deploymentInfo.addListener(new ListenerInfo(UndertowNodesRegistrationManagementWrapper.class, (InstanceFactory<UndertowNodesRegistrationManagementWrapper>) () -> {
- UndertowNodesRegistrationManagementWrapper listener = new UndertowNodesRegistrationManagementWrapper(nodesRegistrationManagement);
- return new ImmediateInstanceHandle<>(listener);
- }));
- }
-
- protected ServletKeycloakAuthMech createAuthenticationMechanism(DeploymentInfo deploymentInfo, AdapterDeploymentContext deploymentContext, UndertowUserSessionManagement userSessionManagement,
- NodesRegistrationManagement nodesRegistrationManagement) {
- log.debug("creating ServletKeycloakAuthMech");
- String errorPage = getErrorPage(deploymentInfo);
- return new ServletKeycloakAuthMech(deploymentContext, userSessionManagement, nodesRegistrationManagement, deploymentInfo.getConfidentialPortManager(), errorPage);
- }
-
- protected String getErrorPage(DeploymentInfo deploymentInfo) {
- LoginConfig loginConfig = deploymentInfo.getLoginConfig();
- String errorPage = null;
- if (loginConfig != null) {
- errorPage = loginConfig.getErrorPage();
- }
- return errorPage;
- }
-
-}
diff --git a/container/src/main/java/org/openremote/container/security/keycloak/UndertowNodesRegistrationManagementWrapper.java b/container/src/main/java/org/openremote/container/security/keycloak/UndertowNodesRegistrationManagementWrapper.java
deleted file mode 100644
index e75af31be..000000000
--- a/container/src/main/java/org/openremote/container/security/keycloak/UndertowNodesRegistrationManagementWrapper.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright 2023, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.container.security.keycloak;
-
-import jakarta.servlet.ServletContextEvent;
-import jakarta.servlet.ServletContextListener;
-import org.keycloak.adapters.NodesRegistrationManagement;
-
-/**
- * This is a copy of the same class from the now obsolete keycloak-undertow-adapter but for jakarta EE.
- *
- */
-// TODO: Move to a standard OIDC adapter
-public class UndertowNodesRegistrationManagementWrapper implements ServletContextListener {
-
- private final NodesRegistrationManagement delegate;
-
- public UndertowNodesRegistrationManagementWrapper(NodesRegistrationManagement delegate) {
- this.delegate = delegate;
- }
-
- @Override
- public void contextDestroyed(ServletContextEvent sce) {
- delegate.stop();
- }
-}
diff --git a/container/src/main/java/org/openremote/container/web/RealmPathExtractorFilter.java b/container/src/main/java/org/openremote/container/web/RealmPathExtractorFilter.java
index 9445e40ae..683f7b73a 100644
--- a/container/src/main/java/org/openremote/container/web/RealmPathExtractorFilter.java
+++ b/container/src/main/java/org/openremote/container/web/RealmPathExtractorFilter.java
@@ -19,62 +19,127 @@
*/
package org.openremote.container.web;
-import jakarta.ws.rs.container.ContainerRequestContext;
-import jakarta.ws.rs.container.ContainerRequestFilter;
-import jakarta.ws.rs.container.PreMatching;
-import jakarta.ws.rs.core.PathSegment;
-import jakarta.ws.rs.core.UriBuilder;
-import jakarta.ws.rs.core.UriInfo;
-import jakarta.ws.rs.ext.Provider;
-import org.openremote.model.Constants;
+
+import jakarta.servlet.*;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequestWrapper;
+import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
-import java.net.URI;
-import java.util.List;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.*;
+
+import static org.openremote.model.Constants.REALM_PARAM_NAME;
/**
- * A JAX-RS filter that removes the realm from the full request path at the specified path segment index and adds it as
- * a {@link org.openremote.model.Constants#REALM_PARAM_NAME} request header. If the
+ * A servlet {@link Filter} that removes the realm from the full request path at the specified path segment index and
+ * adds it as a {@link org.openremote.model.Constants#REALM_PARAM_NAME} request header. If the
* {@link org.openremote.model.Constants#REALM_PARAM_NAME} header is already set, this filter does nothing.
*/
-@Provider
-@PreMatching
-public class RealmPathExtractorFilter implements ContainerRequestFilter {
+public class RealmPathExtractorFilter implements Filter {
+
+ private final int realmPathIndex;
+
+ public RealmPathExtractorFilter(int realmPathIndex) {
+ this.realmPathIndex = realmPathIndex;
+ }
+
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
+
+ if (!(request instanceof HttpServletRequest req) || !(response instanceof HttpServletResponse)) {
+ chain.doFilter(request, response);
+ return;
+ }
+
+ // Do nothing if header already present
+ if (req.getHeader(REALM_PARAM_NAME) != null) {
+ chain.doFilter(request, response);
+ return;
+ }
- protected final int realmPathIndex;
+ String requestUri = req.getRequestURI(); // includes contextPath
+ String contextPath = Optional.ofNullable(req.getContextPath()).orElse("");
+ String pathWithinApp = requestUri.startsWith(contextPath) ? requestUri.substring(contextPath.length()) : requestUri;
- public RealmPathExtractorFilter(int realmPathIndex) {
- this.realmPathIndex = realmPathIndex;
- }
+ // Split into non-empty segments
+ List<String> segments = new ArrayList<>();
+ for (String s : pathWithinApp.split("/")) {
+ if (!s.isEmpty()) segments.add(s);
+ }
- @Override
- public void filter(ContainerRequestContext requestContext) throws IOException {
+ if (segments.size() <= realmPathIndex) {
+ // Not enough segments to extract realm; just continue
+ chain.doFilter(request, response);
+ return;
+ }
- // Do nothing if the realm header is already set
- if (requestContext.getHeaders().containsKey(Constants.REALM_PARAM_NAME)) {
- return;
- }
+ String realm = segments.get(realmPathIndex);
- UriInfo uriInfo = requestContext.getUriInfo();
- List<PathSegment> pathSegments = uriInfo.getPathSegments();
+ // Build a rewritten path with the realm segment removed
+ StringBuilder rewrittenPath = new StringBuilder();
+ rewrittenPath.append(contextPath);
+ for (int i = 0; i < segments.size(); i++) {
+ if (i == realmPathIndex) continue;
+ rewrittenPath.append("/").append(segments.get(i));
+ }
+ if (rewrittenPath.isEmpty()) {
+ rewrittenPath.append("/");
+ }
- if (pathSegments != null && pathSegments.size() > realmPathIndex) {
- String realm = pathSegments.get(realmPathIndex).getPath();
- requestContext.getHeaders().add(Constants.REALM_PARAM_NAME, realm);
+ HttpServletRequestWrapper wrapped = new HttpServletRequestWrapper(req) {
- // Build new URI with the realm segment removed
- UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
- for (int i = 0; i < pathSegments.size(); i++) {
- if (i != realmPathIndex) {
- uriBuilder.path(pathSegments.get(i).getPath());
+ @Override
+ public String getHeader(String name) {
+ if (REALM_PARAM_NAME.equalsIgnoreCase(name)) {
+ return realm;
+ }
+ return super.getHeader(name);
}
- }
- uriBuilder.replaceQuery(uriInfo.getRequestUri().getRawQuery());
- uriBuilder.fragment(uriInfo.getRequestUri().getFragment());
- URI newUri = uriBuilder.build();
+ @Override
+ public Enumeration<String> getHeaders(String name) {
+ if (REALM_PARAM_NAME.equalsIgnoreCase(name)) {
+ return Collections.enumeration(List.of(realm));
+ }
+ return super.getHeaders(name);
+ }
+
+ @Override
+ public Enumeration<String> getHeaderNames() {
+ Set<String> names = new LinkedHashSet<>();
+ Enumeration<String> e = super.getHeaderNames();
+ while (e.hasMoreElements()) {
+ names.add(e.nextElement());
+ }
+ // Ensure it exists even if missing originally
+ names.add(REALM_PARAM_NAME);
+ return Collections.enumeration(names);
+ }
+
+ @Override
+ public String getRequestURI() {
+ return rewrittenPath.toString();
+ }
+
+ @Override
+ public StringBuffer getRequestURL() {
+ // Rebuild from original URL but swap path. Keep scheme/host/port.
+ StringBuffer original = super.getRequestURL();
+ try {
+ URL url = new URL(original.toString());
+ int port = url.getPort();
+ String authority = port == -1 ? url.getHost() : (url.getHost() + ":" + port);
+ return new StringBuffer(url.getProtocol() + "://" + authority + getRequestURI());
+ } catch (MalformedURLException ex) {
+ // Fallback: best-effort
+ return new StringBuffer(original.substring(0, original.indexOf(super.getRequestURI())) + getRequestURI());
+ }
+ }
+ };
- requestContext.setRequestUri(newUri);
- }
- }
+ chain.doFilter(wrapped, response);
+ }
}
diff --git a/container/src/main/java/org/openremote/container/web/SecurityFilter.java b/container/src/main/java/org/openremote/container/web/SecurityServletFilter.java
similarity index 74%
rename from container/src/main/java/org/openremote/container/web/SecurityFilter.java
rename to container/src/main/java/org/openremote/container/web/SecurityServletFilter.java
index 5751be382..67a7a3a70 100644
--- a/container/src/main/java/org/openremote/container/web/SecurityFilter.java
+++ b/container/src/main/java/org/openremote/container/web/SecurityServletFilter.java
@@ -26,15 +26,16 @@ import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
- * A security filter that will check if the request is authenticated and that the user has all the specified roles
- * by calling {@link HttpServletRequest#isUserInRole} for each {@link #requiredRoles}
+ * A security filter that will check if the request is authenticated and that the user has any of the specified roles
+ * by calling {@link HttpServletRequest#isUserInRole} for each {@link #rolesAllowed} until one of them is true. To be
+ * used by non JAX-RS servlet deployments to mimic {@link jakarta.annotation.security.RolesAllowed}
*/
-public class SecurityFilter implements Filter {
+public class SecurityServletFilter implements Filter {
- final protected String[] requiredRoles;
+ final protected String[] rolesAllowed;
- public SecurityFilter(String[] requiredRoles) {
- this.requiredRoles = requiredRoles;
+ public SecurityServletFilter(String[] rolesAllowed) {
+ this.rolesAllowed = rolesAllowed;
}
@Override
@@ -43,15 +44,15 @@ public class SecurityFilter implements Filter {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
- boolean userHasAllRoles = true;
- for (String requiredRole : requiredRoles) {
- if (!req.isUserInRole(requiredRole)) {
- userHasAllRoles = false;
+ boolean userHasRole = false;
+ for (String allowedRole : rolesAllowed) {
+ if (req.isUserInRole(allowedRole)) {
+ userHasRole = true;
break;
}
}
- if (userHasAllRoles) {
+ if (userHasRole) {
chain.doFilter(request, response);
} else {
if (req.getUserPrincipal() == null) {
diff --git a/container/src/main/java/org/openremote/container/web/WebResource.java b/container/src/main/java/org/openremote/container/web/WebResource.java
index bacaaa0e6..a47be5a6d 100644
--- a/container/src/main/java/org/openremote/container/web/WebResource.java
+++ b/container/src/main/java/org/openremote/container/web/WebResource.java
@@ -19,16 +19,14 @@
*/
package org.openremote.container.web;
-import org.keycloak.KeycloakPrincipal;
-import org.openremote.model.Container;
-import org.openremote.container.security.AuthContext;
-import org.openremote.container.security.basic.BasicAuthContext;
-import org.openremote.container.security.keycloak.AccessTokenAuthContext;
-
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.*;
+import org.openremote.container.security.AuthContext;
+import org.openremote.container.security.TokenPrincipal;
+import org.openremote.container.security.basic.BasicAuthContext;
+
import java.security.Principal;
import static jakarta.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
@@ -69,21 +67,14 @@ public class WebResource implements AuthContext {
public AuthContext getAuthContext() {
// The securityContext is a thread-local proxy, careful when/how you call it
Principal principal = securityContext.getUserPrincipal();
- if (principal == null) {
- return null;
- }
-
- if (principal instanceof KeycloakPrincipal) {
- KeycloakPrincipal<?> keycloakPrincipal = (KeycloakPrincipal<?>) principal;
- return new AccessTokenAuthContext(
- keycloakPrincipal.getKeycloakSecurityContext().getRealm(),
- keycloakPrincipal.getKeycloakSecurityContext().getToken()
- );
- } else if (principal instanceof BasicAuthContext) {
- return (BasicAuthContext) principal;
- } else {
- throw new WebApplicationException("Unsupported user principal type: " + principal, INTERNAL_SERVER_ERROR);
- }
+ return switch (principal) {
+ case null -> null;
+ case TokenPrincipal tokenPrincipal -> tokenPrincipal;
+ case BasicAuthContext basicAuthContext -> basicAuthContext;
+ default ->
+ throw new WebApplicationException("Unsupported user principal type: " + principal, INTERNAL_SERVER_ERROR);
+ };
+
}
// Convenience methods
diff --git a/container/src/main/java/org/openremote/container/web/WebService.java b/container/src/main/java/org/openremote/container/web/WebService.java
index 137ba9c87..59a8420cb 100644
--- a/container/src/main/java/org/openremote/container/web/WebService.java
+++ b/container/src/main/java/org/openremote/container/web/WebService.java
@@ -39,9 +39,7 @@ import io.undertow.servlet.Servlets;
import io.undertow.servlet.api.*;
import io.undertow.servlet.handlers.DefaultServlet;
import io.undertow.servlet.util.ImmediateInstanceFactory;
-import io.undertow.servlet.util.ImmediateInstanceHandle;
import io.undertow.util.Headers;
-import io.undertow.util.HttpString;
import io.undertow.websockets.core.WebSocketChannel;
import jakarta.servlet.*;
import jakarta.validation.constraints.NotNull;
@@ -71,7 +69,9 @@ import java.util.stream.Collectors;
import static java.lang.System.Logger.Level.*;
import static org.openremote.container.web.CORSConfig.DEFAULT_CORS_ALLOW_ALL;
-import static org.openremote.model.Constants.*;
+import static org.openremote.container.web.WebTargetBuilder.getClient;
+import static org.openremote.model.Constants.OR_ADDITIONAL_HOSTNAMES;
+import static org.openremote.model.Constants.OR_HOSTNAME;
import static org.openremote.model.util.MapAccess.*;
public abstract class WebService implements ContainerService {
@@ -199,6 +199,9 @@ public abstract class WebService implements ContainerService {
LOG.log(INFO, "Deploying undertow servlet deployment: name=" + deploymentInfo.getDeploymentName() + ", path=" + pathPrefix + ", secure=" + !deploymentInfo.isSecurityDisabled());
+ // This will catch anything not handled by Resteasy/Servlets, such as IOExceptions "at the wrong time"
+ deploymentInfo.setExceptionHandler(new WebServiceExceptions.ServletExceptionHandler(devMode));
+
try {
DeploymentManager manager = Servlets.defaultContainer().addDeployment(deploymentInfo);
manager.deploy();
@@ -255,18 +258,12 @@ public abstract class WebService implements ContainerService {
* Get standard JAX-RS providers that are used in the deployment with optional realm extraction from the request
* path
*/
- public static List<Object> getStandardProviders(boolean devMode, Integer realmIndex) {
- List<Object> providers = Lists.newArrayList(
+ public static List<Object> getStandardProviders(boolean devMode) {
+ return Lists.newArrayList(
new WebServiceExceptions.JAXRSExceptionMapper(devMode),
new JacksonConfig(),
new ClientErrorExceptionHandler()
);
-
- if (realmIndex != null) {
- providers.addFirst(new RealmPathExtractorFilter(realmIndex));
- }
-
- return providers;
}
/**
@@ -279,7 +276,6 @@ public abstract class WebService implements ContainerService {
}
protected Undertow.Builder build(Container container, Undertow.Builder builder) {
-
HttpHandler handler = new WebServiceExceptions.RootUndertowExceptionHandler(devMode, pathHandler);
if (getBoolean(container.getConfig(), OR_WEBSERVER_DUMP_REQUESTS, OR_WEBSERVER_DUMP_REQUESTS_DEFAULT)) {
@@ -314,7 +310,14 @@ public abstract class WebService implements ContainerService {
.addServletContainerInitializer(new ServletContainerInitializerInfo(servletContainerInitializerClass, null))
.setClassLoader(this.getClass().getClassLoader());
- configureDeploymentInfo(deploymentInfo, realmIndex, secure, corsOverride);
+ ServletContainerInitializer containerInitializer = (c, ctx) ->
+ configureServlet(ctx, secure, realmIndex, corsOverride);
+
+ InstanceFactory<ServletContainerInitializer> factory = new ImmediateInstanceFactory<>(containerInitializer);
+ deploymentInfo.addServletContainerInitializer(
+ new ServletContainerInitializerInfo(containerInitializer.getClass(), factory, Collections.emptySet())
+ );
+
deploy(deploymentInfo, false);
}
@@ -352,7 +355,14 @@ public abstract class WebService implements ContainerService {
.addListeners(Servlets.listener(listenerClass, factory))
.setClassLoader(this.getClass().getClassLoader());
- configureDeploymentInfo(deploymentInfo, realmIndex, secure, corsOverride);
+ ServletContainerInitializer containerInitializer = (c, ctx) ->
+ configureServlet(ctx, secure, realmIndex, corsOverride);
+
+ InstanceFactory<ServletContainerInitializer> initFactory = new ImmediateInstanceFactory<>(containerInitializer);
+ deploymentInfo.addServletContainerInitializer(
+ new ServletContainerInitializerInfo(containerInitializer.getClass(), initFactory, Collections.emptySet())
+ );
+
deploy(deploymentInfo, false);
}
@@ -364,7 +374,8 @@ public abstract class WebService implements ContainerService {
String deploymentPath,
String deploymentName,
ResourceSource[] resourceSources,
- String[] requiredRoles,
+ String[] allowedRoles,
+ Integer realmIndex,
CORSConfig corsOverride) {
if (resourceSources == null || resourceSources.length == 0) {
@@ -392,27 +403,28 @@ public abstract class WebService implements ContainerService {
MIME_TYPES.forEach((ext, mimeType) -> deploymentInfo.addMimeMapping(new MimeMapping(ext, mimeType)));
- Filter alreadyGzippedFilter = new AlreadyGZippedFilter(MIME_TYPES_ALREADY_GZIPPED);
- FilterInfo alreadyGzippedFilterInfo = Servlets.filter(
- "Already GZipped Filter",
- AlreadyGZippedFilter.class,
- () -> new ImmediateInstanceHandle<>(alreadyGzippedFilter)).setAsyncSupported(true);
- deploymentInfo.addFilter(alreadyGzippedFilterInfo);
- deploymentInfo.addFilterUrlMapping( "Already GZipped Filter","/*", DispatcherType.REQUEST);
-
- if (requiredRoles != null && requiredRoles.length > 0) {
- Filter securityFilter = new SecurityFilter(requiredRoles);
- FilterInfo securityFilterInfo = Servlets.filter("Security Filter", SecurityFilter.class, () -> new ImmediateInstanceHandle<>(securityFilter))
- .setAsyncSupported(true);
- deploymentInfo.addFilter(securityFilterInfo);
- deploymentInfo.addFilterUrlMapping( "Security Filter","/*", DispatcherType.REQUEST);
- }
+ ServletContainerInitializer containerInitializer = (c, ctx) -> {
+ configureServlet(ctx, allowedRoles != null && allowedRoles.length > 0, realmIndex, corsOverride);
+
+ // Add a security filter to mimic JAX-RS @RolesAllowed annotation for file serving
+ if (allowedRoles != null && allowedRoles.length > 0) {
+ Filter securityFilter = new SecurityServletFilter(allowedRoles);
+ FilterRegistration.Dynamic securityRegistration = ctx.addFilter(SecurityServletFilter.class.getSimpleName(), securityFilter);
+ securityRegistration.setAsyncSupported(true);
+ securityRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
+ }
+
+ Filter alreadyGzippedFilter = new AlreadyGZippedFilter(MIME_TYPES_ALREADY_GZIPPED);
+ FilterRegistration.Dynamic alreadyGzippedRegistration = ctx.addFilter(AlreadyGZippedFilter.class.getSimpleName(), alreadyGzippedFilter);
+ alreadyGzippedRegistration.setAsyncSupported(true);
+ alreadyGzippedRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
+ };
+
+ InstanceFactory<ServletContainerInitializer> factory = new ImmediateInstanceFactory<>(containerInitializer);
+ deploymentInfo.addServletContainerInitializer(
+ new ServletContainerInitializerInfo(containerInitializer.getClass(), factory, Collections.emptySet())
+ );
- configureDeploymentInfo(
- deploymentInfo,
- null,
- requiredRoles != null && requiredRoles.length > 0,
- corsOverride);
deploy(deploymentInfo, true);
}
@@ -426,10 +438,10 @@ public abstract class WebService implements ContainerService {
throw new UnsupportedOperationException("ResourceSource not currently supported");
}
- public void configureDeploymentInfo(
- DeploymentInfo deploymentInfo,
- Integer realmIndex,
+ public void configureServlet(
+ ServletContext ctx,
boolean secure,
+ Integer realmIndex,
CORSConfig corsOverride) {
if (corsOverride == null) {
@@ -437,81 +449,42 @@ public abstract class WebService implements ContainerService {
corsOverride = new CORSConfig();
}
- // TODO: Remove this handler wrapper once JAX-RS RealmPathExtractorFilter can be utilised before security is applied
- if (realmIndex != null) {
- deploymentInfo.addInitialHandlerChainWrapper(handler -> {
-
- return exchange -> {
- // Do nothing if the realm header is already set
- if (exchange.getRequestHeaders().contains(REALM_PARAM_NAME)) {
- handler.handleRequest(exchange);
- return;
- }
-
- String relativePath = exchange.getRelativePath();
- StringBuilder newRelativePathBuilder = new StringBuilder();
- String realm = null;
- int segmentIndex = 0;
- int start = 1; // Path starts with '/'
-
- for (int i = 1; i <= relativePath.length(); i++) {
- if (i == relativePath.length() || relativePath.charAt(i) == '/') {
- if (i > start) { // Found a segment
- if (segmentIndex == realmIndex) {
- realm = relativePath.substring(start, i);
- } else {
- newRelativePathBuilder.append('/').append(relativePath, start, i);
- }
- segmentIndex++;
- }
- start = i + 1;
- }
- }
-
- if (realm != null) {
- exchange.getRequestHeaders().put(HttpString.tryFromString(REALM_PARAM_NAME), realm);
-
- String newRelativePath = !newRelativePathBuilder.isEmpty() ? newRelativePathBuilder.toString() : "/";
- String newRequestPath = deploymentInfo.getContextPath() + newRelativePath;
- exchange.setRequestURI(newRequestPath);
- exchange.setRelativePath(newRelativePath);
- exchange.setRequestPath(newRequestPath);
- }
-
- handler.handleRequest(exchange);
- };
- });
- }
-
if (secure) {
if (identityService == null)
throw new IllegalStateException(
"No identity service found, make sure " + IdentityService.class.getName() + " is added before this service"
);
- identityService.secureDeployment(deploymentInfo);
}
- Filter loggingFilter = new LoggingFilter(devMode);
- FilterInfo loggingFilterInfo = Servlets.filter(
- "Logging Filter",
- LoggingFilter.class,
- () -> new ImmediateInstanceHandle<>(loggingFilter)).setAsyncSupported(true);
- deploymentInfo.addFilter(loggingFilterInfo);
- deploymentInfo.addFilterUrlMapping("Logging Filter","/*", DispatcherType.REQUEST);
+ // Do all filter registration using the ServletContext for sane predictable ordering
+ // CORS filter 1st
// Cannot set config on constructor as init method will overwrite it
CORSFilter corsFilter = new CORSFilter();
+ FilterRegistration.Dynamic corsRegistration = ctx.addFilter(CORSFilter.class.getSimpleName(), corsFilter);
+ corsRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST),false,"/*");
+ corsRegistration.setAsyncSupported(true);
+ getCORSConfiguration(corsOverride).forEach((k, v) -> corsRegistration.setInitParameter(k.toString(), v.toString()));
+
+ if (realmIndex != null) {
+ // The realm extraction from path
+ RealmPathExtractorFilter realmPathExtractorFilter = new RealmPathExtractorFilter(realmIndex);
+ FilterRegistration.Dynamic realmExtractorRegistration = ctx.addFilter(RealmPathExtractorFilter.class.getSimpleName(), realmPathExtractorFilter);
+ realmExtractorRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
+ realmExtractorRegistration.setAsyncSupported(true);
+ }
- FilterInfo corsFilterInfo = Servlets.filter(
- "CORS Filter",
- CORSFilter.class,
- () -> new ImmediateInstanceHandle<>(corsFilter)).setAsyncSupported(true);
- getCORSConfiguration(corsOverride).forEach((k,v) -> corsFilterInfo.addInitParam(k.toString(), v.toString()));
- deploymentInfo.addFilter(corsFilterInfo);
- deploymentInfo.addFilterUrlMapping("CORS Filter","/*", DispatcherType.REQUEST);
+ // Then logging
+ FilterRegistration.Dynamic loggingRegistration = ctx.addFilter(LoggingFilter.class.getSimpleName(), new LoggingFilter(devMode));
+ loggingRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST),true,"/*");
+ loggingRegistration.setAsyncSupported(true);
- // This will catch anything not handled by Resteasy/Servlets, such as IOExceptions "at the wrong time"
- deploymentInfo.setExceptionHandler(new WebServiceExceptions.ServletExceptionHandler(devMode));
+ // Then security
+ if (secure) {
+ FilterRegistration.Dynamic securityRegistration = identityService.secureDeployment(ctx);
+ securityRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST),true,"/*");
+ securityRegistration.setAsyncSupported(true);
+ }
}
public Undertow getUndertow() {
diff --git a/container/src/main/resources/META-INF/services/io.undertow.servlet.ServletExtension b/container/src/main/resources/META-INF/services/io.undertow.servlet.ServletExtension
deleted file mode 100644
index 88f1892fa..000000000
--- a/container/src/main/resources/META-INF/services/io.undertow.servlet.ServletExtension
+++ /dev/null
@@ -1,18 +0,0 @@
-#
-# Copyright 2016 Red Hat, Inc. and/or its affiliates
-# and other contributors as indicated by the @author tags.
-#
-# Licensed 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.
-#
-
-org.keycloak.adapters.undertow.KeycloakServletExtension
diff --git a/extension/energy/src/test/groovy/org/openremote/extension/energy/ForecastWindServiceTest.groovy b/extension/energy/src/test/groovy/org/openremote/extension/energy/ForecastWindServiceTest.groovy
index 76d33a4e1..fd4ec0c2c 100644
--- a/extension/energy/src/test/groovy/org/openremote/extension/energy/ForecastWindServiceTest.groovy
+++ b/extension/energy/src/test/groovy/org/openremote/extension/energy/ForecastWindServiceTest.groovy
@@ -33,7 +33,7 @@ class ForecastWindServiceTest extends Specification implements ManagerContainerT
@Shared
def mockServer = new ClientRequestFilter() {
- boolean finished = true
+ boolean finished = false
@Override
void filter(ClientRequestContext requestContext) throws IOException {
diff --git a/gradle.properties b/gradle.properties
index 3c4024a7a..2d08c3108 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -67,7 +67,7 @@ prometheusVersion=1.6.1
micrometerVersion=1.16.5
jdomVersion = 2.0.6.1
apacheMINAVersion = 2.16.0
-bouncyCastleVersion = 1.81
+bouncyCastleVersion = 1.83
victoolsJsonSchemaGeneratorVersion = 4.38.0
moquetteVersion = 0.18.0
corsFilterVersion = 3.1
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
index 3db1cf025..da2ef5cf7 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
@@ -154,7 +154,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
}
// Users must have write attributes role
- if (authContext != null && !authContext.hasResourceRoleOrIsSuperUser(ClientRole.WRITE_ATTRIBUTES.getValue(),
+ if (authContext != null && !authContext.hasResourceRole(ClientRole.WRITE_ATTRIBUTES.getValue(),
Constants.KEYCLOAK_CLIENT_ID)) {
LOG.log(System.Logger.Level.DEBUG, "User doesn't have required role '" + ClientRole.WRITE_ATTRIBUTES + "': username=" + authContext.getUsername() + ", userRealm=" + authContext.getAuthenticatedRealmName());
return false;
diff --git a/manager/src/main/java/org/openremote/manager/datapoint/AssetPredictedDatapointService.java b/manager/src/main/java/org/openremote/manager/datapoint/AssetPredictedDatapointService.java
index 8c3bc1a84..13387e66d 100644
--- a/manager/src/main/java/org/openremote/manager/datapoint/AssetPredictedDatapointService.java
+++ b/manager/src/main/java/org/openremote/manager/datapoint/AssetPredictedDatapointService.java
@@ -28,13 +28,13 @@ import org.openremote.manager.web.ManagerWebService;
import org.openremote.model.Constants;
import org.openremote.model.Container;
import org.openremote.model.asset.Asset;
-import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.attribute.Attribute;
-import org.openremote.model.datapoint.AssetPredictedDatapointEvent;
+import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.datapoint.AssetPredictedDatapoint;
+import org.openremote.model.datapoint.AssetPredictedDatapointEvent;
import org.openremote.model.datapoint.ValueDatapoint;
-import org.openremote.model.event.shared.EventSubscription;
import org.openremote.model.event.shared.EventFilter;
+import org.openremote.model.event.shared.EventSubscription;
import org.openremote.model.security.ClientRole;
import org.openremote.model.value.MetaItemType;
@@ -103,7 +103,7 @@ public class AssetPredictedDatapointService extends AbstractDatapointService<Ass
});
}
- return auth.hasResourceRoleOrIsSuperUser(ClientRole.READ_ASSETS.getValue(), Constants.KEYCLOAK_CLIENT_ID)
+ return (auth.isSuperUser() || auth.hasResourceRole(ClientRole.READ_ASSETS.getValue(), Constants.KEYCLOAK_CLIENT_ID))
&& identityService.getIdentityProvider().isRealmActiveAndAccessible(auth, requestedRealm);
});
diff --git a/manager/src/main/java/org/openremote/manager/event/ClientEventService.java b/manager/src/main/java/org/openremote/manager/event/ClientEventService.java
index 6a8288849..aa92013e0 100644
--- a/manager/src/main/java/org/openremote/manager/event/ClientEventService.java
+++ b/manager/src/main/java/org/openremote/manager/event/ClientEventService.java
@@ -21,16 +21,15 @@ package org.openremote.manager.event;
import io.undertow.websockets.core.WebSocketChannel;
import io.undertow.websockets.spi.WebSocketHttpExchange;
+import jakarta.security.enterprise.AuthenticationException;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.undertow.UndertowComponent;
import org.apache.camel.component.undertow.UndertowConstants;
import org.apache.camel.component.undertow.UndertowHostKey;
-import org.keycloak.KeycloakPrincipal;
import org.openremote.container.message.MessageBrokerService;
import org.openremote.container.security.AuthContext;
-import org.openremote.container.security.basic.BasicAuthContext;
-import org.openremote.container.security.keycloak.AccessTokenAuthContext;
+import org.openremote.container.security.TokenPrincipal;
import org.openremote.container.timer.TimerService;
import org.openremote.manager.gateway.GatewayService;
import org.openremote.manager.security.ManagerIdentityService;
@@ -44,11 +43,15 @@ import org.openremote.model.event.Event;
import org.openremote.model.event.RespondableEvent;
import org.openremote.model.event.TriggeredEventSubscription;
import org.openremote.model.event.shared.*;
+import org.openremote.model.http.RequestParams;
import org.openremote.model.security.User;
import org.openremote.model.syslog.SyslogEvent;
import org.openremote.model.util.Pair;
+import org.openremote.model.util.TextUtil;
import java.io.IOException;
+import java.net.URLDecoder;
+import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@@ -57,6 +60,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.function.Consumer;
+import static jakarta.ws.rs.core.HttpHeaders.AUTHORIZATION;
import static java.lang.System.Logger.Level.*;
import static org.openremote.manager.asset.AssetProcessingService.ATTRIBUTE_EVENT_PROCESSOR;
import static org.openremote.manager.asset.AssetProcessingService.ATTRIBUTE_EVENT_ROUTE_CONFIG_ID;
@@ -350,61 +354,65 @@ public class ClientEventService extends RouteBuilder implements ContainerService
switch (eventType) {
case ONOPEN -> {
WebSocketHttpExchange httpExchange = exchange.getIn().getHeader(UndertowConstants.EXCHANGE, WebSocketHttpExchange.class);
- String realm = httpExchange.getRequestHeader(Constants.REALM_PARAM_NAME);
- Principal principal = httpExchange.getUserPrincipal();
+ String realm = getHeaderThenQueryParam(httpExchange, REALM_PARAM_NAME, REALM_PARAM_NAME);
+ Principal principal = null;
AuthContext authContext = null;
-
- if (principal instanceof KeycloakPrincipal<?> keycloakPrincipal) {
- authContext = new AccessTokenAuthContext(
- keycloakPrincipal.getKeycloakSecurityContext().getRealm(),
- keycloakPrincipal.getKeycloakSecurityContext().getToken()
- );
- } else if (principal instanceof BasicAuthContext) {
- authContext = (BasicAuthContext) principal;
- } else if (principal != null) {
- LOG.log(INFO, "Unsupported user principal type: " + principal);
- }
-
- // Set an idle timeout value for service account connections; browsers don't reliably support
- // ping/pong frames so we can't be too aggressive with those connections but other clients
- // should implement ping/pong
- if (authContext != null && authContext.getUsername().startsWith(User.SERVICE_ACCOUNT_PREFIX)) {
- webSocketChannel.setIdleTimeout(30000);
+ String authorization = getHeaderThenQueryParam(httpExchange, AUTHORIZATION, AUTHORIZATION);
+
+ if (!TextUtil.isNullOrEmpty(authorization)) {
+ authorization = RequestParams.getBearerAuth(authorization);
+ try {
+ principal = identityService.verify(realm, authorization);
+ } catch (AuthenticationException e) {
+ LOG.log(INFO, "Failed to verify client identity '" + e.getMessage() + "': " + webSocketChannel.getSourceAddress());
+ }
+
+ if (principal instanceof AuthContext ac) {
+ LOG.log(DEBUG, "Client identity verified '" + ((TokenPrincipal) principal).getUsername() + "': " + webSocketChannel.getSourceAddress());
+ authContext = ac;
+ }
}
- // Push auth and realm into channel for future use
- webSocketChannel.setAttribute(Constants.AUTH_CONTEXT, authContext);
- webSocketChannel.setAttribute(Constants.REALM_PARAM_NAME, realm);
-
- exchange.getIn().setHeader(Constants.AUTH_CONTEXT, authContext);
- exchange.getIn().setHeader(Constants.REALM_PARAM_NAME, realm);
- exchange.getIn().setHeader(SESSION_OPEN, true);
- sessionChannels.put(getSessionKey(exchange), webSocketChannel);
- LOG.log(DEBUG, "Client connection created: " + webSocketChannel.getSourceAddress());
+ // Set an idle timeout value for service account connections; browsers don't reliably support
+ // ping/pong frames so we can't be too aggressive with those connections but other clients
+ // should implement ping/pong
+ if (authContext != null && authContext.getUsername().startsWith(User.SERVICE_ACCOUNT_PREFIX)) {
+ webSocketChannel.setIdleTimeout(30000);
+ }
+
+ // Push auth and realm into channel for future use
+ webSocketChannel.setAttribute(AUTH_CONTEXT, authContext);
+ webSocketChannel.setAttribute(REALM_PARAM_NAME, realm);
+
+ exchange.getIn().setHeader(AUTH_CONTEXT, authContext);
+ exchange.getIn().setHeader(REALM_PARAM_NAME, realm);
+ exchange.getIn().setHeader(SESSION_OPEN, true);
+ sessionChannels.put(getSessionKey(exchange), webSocketChannel);
+ LOG.log(DEBUG, "Client connection created: " + webSocketChannel.getSourceAddress());
}
case ONCLOSE, ONERROR -> {
- AuthContext authContext = (AuthContext) webSocketChannel.getAttribute(Constants.AUTH_CONTEXT);
- String realm = (String) webSocketChannel.getAttribute(Constants.REALM_PARAM_NAME);
- String sessionKey = getSessionKey(exchange);
-
- exchange.getIn().setHeader(Constants.AUTH_CONTEXT, authContext);
- exchange.getIn().setHeader(Constants.REALM_PARAM_NAME, realm);
-
- if (eventType == UndertowConstants.EventType.ONCLOSE) {
- LOG.log(DEBUG, "Client connection closed: " + webSocketChannel.getSourceAddress());
- exchange.getIn().setHeader(SESSION_CLOSE, true);
- } else {
- LOG.log(DEBUG, "Client connection error: " + webSocketChannel.getSourceAddress());
- closeWebsocketChannel(sessionKey, webSocketChannel);
- exchange.getIn().setHeader(SESSION_CLOSE_ERROR, true);
- }
-
- LOG.log(TRACE, "Removing subscriptions for session: " + sessionKey);
- sessionChannels.remove(getSessionKey(exchange));
- websocketSessionSubscriptionConsumers.computeIfPresent(sessionKey, (s, subscriptionConsumers) -> {
- subscriptionConsumers.forEach((subscriptionKey, consumer) -> removeSubscription(consumer));
- return null;
- });
+ AuthContext authContext = (AuthContext) webSocketChannel.getAttribute(AUTH_CONTEXT);
+ String realm = (String) webSocketChannel.getAttribute(REALM_PARAM_NAME);
+ String sessionKey = getSessionKey(exchange);
+
+ exchange.getIn().setHeader(AUTH_CONTEXT, authContext);
+ exchange.getIn().setHeader(REALM_PARAM_NAME, realm);
+
+ if (eventType == UndertowConstants.EventType.ONCLOSE) {
+ LOG.log(DEBUG, "Client connection closed: " + webSocketChannel.getSourceAddress());
+ exchange.getIn().setHeader(SESSION_CLOSE, true);
+ } else {
+ LOG.log(DEBUG, "Client connection error: " + webSocketChannel.getSourceAddress());
+ closeWebsocketChannel(sessionKey, webSocketChannel);
+ exchange.getIn().setHeader(SESSION_CLOSE_ERROR, true);
+ }
+
+ LOG.log(TRACE, "Removing subscriptions for session: " + sessionKey);
+ sessionChannels.remove(getSessionKey(exchange));
+ websocketSessionSubscriptionConsumers.computeIfPresent(sessionKey, (s, subscriptionConsumers) -> {
+ subscriptionConsumers.forEach((subscriptionKey, consumer) -> removeSubscription(consumer));
+ return null;
+ });
}
}
@@ -420,11 +428,11 @@ public class ClientEventService extends RouteBuilder implements ContainerService
@SuppressWarnings({"unchecked", "rawtypes"})
void procesInboundEvent(Exchange exchange) {
WebSocketChannel webSocketChannel = exchange.getIn().getHeader(UndertowConstants.CHANNEL, WebSocketChannel.class);
- AuthContext authContext = (AuthContext) webSocketChannel.getAttribute(Constants.AUTH_CONTEXT);
- String realm = (String) webSocketChannel.getAttribute(Constants.REALM_PARAM_NAME);
+ AuthContext authContext = (AuthContext) webSocketChannel.getAttribute(AUTH_CONTEXT);
+ String realm = (String) webSocketChannel.getAttribute(REALM_PARAM_NAME);
- exchange.getIn().setHeader(Constants.AUTH_CONTEXT, authContext);
- exchange.getIn().setHeader(Constants.REALM_PARAM_NAME, realm);
+ exchange.getIn().setHeader(AUTH_CONTEXT, authContext);
+ exchange.getIn().setHeader(REALM_PARAM_NAME, realm);
// Pass to gateway interceptor and abort if it stops the exchange
if (gatewayInterceptor != null) {
@@ -677,4 +685,49 @@ public class ClientEventService extends RouteBuilder implements ContainerService
return getClass().getSimpleName() + "{" +
'}';
}
+
+ protected static String getHeaderThenQueryParam(WebSocketHttpExchange exchange, String headerName, String queryParamName) {
+ if (exchange == null) {
+ return null;
+ }
+
+ String headerValue = exchange.getRequestHeader(headerName);
+ if (headerValue != null && !headerValue.isBlank()) {
+ return headerValue;
+ }
+
+ return getFirstQueryParam(exchange.getQueryString(), queryParamName);
+ }
+
+ protected static String getFirstQueryParam(String queryString, String name) {
+ if (queryString == null || queryString.isBlank() || name == null || name.isBlank()) {
+ return null;
+ }
+
+ // Undertow's queryString is typically the raw part after '?', e.g. "a=1&b=2"
+ String qs = queryString.startsWith("?") ? queryString.substring(1) : queryString;
+
+ for (String part : qs.split("&")) {
+ if (part.isEmpty()) continue;
+
+ int idx = part.indexOf('=');
+ String rawKey = idx >= 0 ? part.substring(0, idx) : part;
+ String rawVal = idx >= 0 ? part.substring(idx + 1) : "";
+
+ String key = urlDecode(rawKey);
+ if (!name.equals(key)) {
+ continue;
+ }
+
+ String val = urlDecode(rawVal);
+ return (val == null || val.isBlank()) ? null : val;
+ }
+
+ return null;
+ }
+
+ protected static String urlDecode(String s) {
+ if (s == null) return null;
+ return URLDecoder.decode(s, StandardCharsets.UTF_8);
+ }
}
diff --git a/manager/src/main/java/org/openremote/manager/event/UndertowHost.java b/manager/src/main/java/org/openremote/manager/event/UndertowHost.java
index 1b1d8e467..d231e0e8d 100644
--- a/manager/src/main/java/org/openremote/manager/event/UndertowHost.java
+++ b/manager/src/main/java/org/openremote/manager/event/UndertowHost.java
@@ -23,15 +23,10 @@ import io.undertow.Undertow;
import io.undertow.server.HttpHandler;
import io.undertow.servlet.Servlets;
import io.undertow.servlet.api.DeploymentInfo;
-import io.undertow.servlet.api.SecurityConstraint;
-import io.undertow.servlet.api.SecurityInfo;
-import io.undertow.servlet.api.WebResourceCollection;
import org.apache.camel.component.undertow.HttpHandlerRegistrationInfo;
import org.apache.camel.component.undertow.UndertowConsumer;
import org.apache.camel.component.undertow.UndertowHostKey;
import org.apache.camel.component.undertow.UndertowHostOptions;
-import org.openremote.container.security.IdentityService;
-import org.openremote.container.security.WebsocketAuthParamHandler;
import org.openremote.container.web.WebService;
import org.openremote.model.Container;
@@ -71,26 +66,12 @@ public class UndertowHost implements org.apache.camel.component.undertow.Underto
}
WebService webService = container.getService(WebService.class);
- IdentityService identityService = container.getService(IdentityService.class);
-
- String path = registrationInfo.getUri().getPath();
- deployment = Servlets.deployment()
- .setDeploymentName(DEPLOYMENT_NAME)
- .setContextPath(path)
- .setClassLoader(getClass().getClassLoader())
- // Add handler to extract authorization and realm query params
- .addInitialHandlerChainWrapper(WebsocketAuthParamHandler::new)
- //httpHandler for servlet is ignored, camel handler is used instead of it
- .addInnerHandlerChainWrapper(h -> handler);
-
- // Require authentication, but authorize specific roles later in Camel
- WebResourceCollection resourceCollection = new WebResourceCollection();
- resourceCollection.addUrlPattern("/*");
- SecurityConstraint constraint = new SecurityConstraint();
- constraint.setEmptyRoleSemantic(SecurityInfo.EmptyRoleSemantic.PERMIT);
- constraint.addWebResourceCollection(resourceCollection);
- deployment.addSecurityConstraints(constraint);
- identityService.secureDeployment(deployment);
+ String path = registrationInfo.getUri().getPath();
+ deployment = Servlets.deployment()
+ .setDeploymentName(DEPLOYMENT_NAME)
+ .setContextPath(path)
+ .setClassLoader(getClass().getClassLoader())
+ .addInitialHandlerChainWrapper(h -> handler);
webService.deploy(deployment, false);
// Caller expects a CamelWebSocketHandler instance
camelHandler = handler;
diff --git a/manager/src/main/java/org/openremote/manager/mqtt/ActiveMQORSecurityManager.java b/manager/src/main/java/org/openremote/manager/mqtt/ActiveMQORSecurityManager.java
index 76ed95936..e5b80bc5a 100644
--- a/manager/src/main/java/org/openremote/manager/mqtt/ActiveMQORSecurityManager.java
+++ b/manager/src/main/java/org/openremote/manager/mqtt/ActiveMQORSecurityManager.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2022, OpenRemote Inc.
+ * Copyright 2026, OpenRemote Inc.
*
* See the CONTRIBUTORS.txt file in the distribution for a
* full listing of individual contributors.
@@ -19,62 +19,53 @@
*/
package org.openremote.manager.mqtt;
+import jakarta.security.enterprise.AuthenticationException;
import org.apache.activemq.artemis.core.config.WildcardConfiguration;
-import org.apache.activemq.artemis.core.config.impl.SecurityConfiguration;
import org.apache.activemq.artemis.core.protocol.mqtt.MQTTUtil;
import org.apache.activemq.artemis.core.security.CheckType;
import org.apache.activemq.artemis.core.security.Role;
-import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection;
-import org.apache.activemq.artemis.spi.core.security.ActiveMQJAASSecurityManager;
-import org.keycloak.KeycloakSecurityContext;
-import org.keycloak.adapters.KeycloakDeployment;
-import org.openremote.container.security.keycloak.KeycloakIdentityProvider;
-import org.openremote.manager.security.AuthorisationService;
-import org.openremote.manager.security.MultiTenantJaasCallbackHandler;
+import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManager5;
+import org.apache.activemq.artemis.spi.core.security.jaas.NoCacheLoginException;
+import org.apache.activemq.artemis.spi.core.security.jaas.RolePrincipal;
+import org.apache.activemq.artemis.spi.core.security.jaas.UserPrincipal;
+import org.openremote.container.security.IdentityProvider;
+import org.openremote.container.security.IdentityService;
+import org.openremote.container.security.OIDCTokenResponse;
+import org.openremote.container.security.TokenPrincipal;
import org.openremote.manager.security.RemotingConnectionPrincipal;
import org.openremote.model.protocol.mqtt.Topic;
import org.openremote.model.syslog.SyslogCategory;
import javax.security.auth.Subject;
-import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
+import java.security.Principal;
+import java.util.HashSet;
import java.util.Set;
-import java.util.function.Function;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
-import static org.apache.activemq.artemis.utils.CertificateUtil.getCertsFromConnection;
import static org.openremote.manager.mqtt.MQTTBrokerService.connectionToString;
-import static org.openremote.model.syslog.SyslogCategory.API;
/**
- * A security manager that uses the {@link org.openremote.manager.security.MultiTenantJaasCallbackHandler} with a
- * dynamic {@link org.keycloak.adapters.KeycloakDeployment} resolver.
- *
- * Unfortunately lots of private methods and fields in super class.
+ * An {@link ActiveMQSecurityManager5} implementation that authenticates the user by either retrieving an access token
+ * on behalf of the service user or validating the supplied access token
*/
-public class ActiveMQORSecurityManager extends ActiveMQJAASSecurityManager {
-
- private static final Logger LOG = SyslogCategory.getLogger(API, ActiveMQORSecurityManager.class);
- protected AuthorisationService authorisationService;
- protected MQTTBrokerService brokerService;
- protected Function<String, KeycloakDeployment> deploymentResolver;
-
- // Duplicate fields due to being private in super class
- protected String certificateConfigName;
- protected String configName;
- protected SecurityConfiguration config;
- protected SecurityConfiguration certificateConfig;
- protected ActiveMQServer server;
-
- public ActiveMQORSecurityManager(AuthorisationService authorisationService, MQTTBrokerService brokerService, Function<String, KeycloakDeployment> deploymentResolver, String configurationName, SecurityConfiguration configuration) {
- super(configurationName, configuration);
- this.authorisationService = authorisationService;
+public class ActiveMQORSecurityManager implements ActiveMQSecurityManager5 {
+ protected static final Logger LOG = SyslogCategory.getLogger(SyslogCategory.API, ActiveMQORSecurityManager.class.getName());
+ public static final String ANONYMOUS_USERNAME = "anonymous";
+ protected static final long TOKEN_TIMEOUT_MILLIS = 10000;
+ protected final MQTTBrokerService brokerService;
+ protected final ExecutorService executorService;
+ protected final IdentityService identityService;
+
+ public ActiveMQORSecurityManager(MQTTBrokerService brokerService, ExecutorService executorService, IdentityService identityService) {
this.brokerService = brokerService;
- this.deploymentResolver = deploymentResolver;
- this.configName = configurationName;
- this.config = configuration;
+ this.executorService = executorService;
+ this.identityService = identityService;
}
protected static Topic fromAddress(String address, WildcardConfiguration wildcardConfiguration) throws IllegalArgumentException {
@@ -82,61 +73,59 @@ public class ActiveMQORSecurityManager extends ActiveMQJAASSecurityManager {
}
@Override
- public Subject authenticate(String user, String password, RemotingConnection remotingConnection, String securityDomain) {
- try {
- return remotingConnection.getSubject() != null ? remotingConnection.getSubject() : getAuthenticatedSubject(user, password, remotingConnection, securityDomain);
- } catch (LoginException e) {
- return null;
- }
- }
+ public Subject authenticate(String user, String password, RemotingConnection remotingConnection, String securityDomain) throws NoCacheLoginException {
- protected Subject getAuthenticatedSubject(String user,
- String password,
- final RemotingConnection remotingConnection,
- final String securityDomain) throws LoginException {
- LoginContext lc;
- String realm = null;
- ClassLoader currentLoader = Thread.currentThread().getContextClassLoader();
- ClassLoader thisLoader = this.getClass().getClassLoader();
-
- if (user != null) {
- String[] realmAndUsername = user.split(":");
- if (realmAndUsername.length == 2) {
- realm = realmAndUsername[0];
- user = realmAndUsername[1];
- }
+ if (remotingConnection.getSubject() != null) {
+ return remotingConnection.getSubject();
}
- try {
- if (thisLoader != currentLoader) {
- Thread.currentThread().setContextClassLoader(thisLoader);
- }
- if (securityDomain != null) {
- lc = new LoginContext(securityDomain, null, new MultiTenantJaasCallbackHandler(deploymentResolver, realm, user, password, remotingConnection), null);
- } else if (certificateConfigName != null && certificateConfigName.length() > 0 && getCertsFromConnection(remotingConnection) != null) {
- lc = new LoginContext(certificateConfigName, null, new MultiTenantJaasCallbackHandler(deploymentResolver, realm, user, password, remotingConnection), certificateConfig);
- } else {
- lc = new LoginContext(configName, null, new MultiTenantJaasCallbackHandler(deploymentResolver, realm, user, password, remotingConnection), config);
- }
- try {
- lc.login();
- } catch (LoginException e) {
- throw e;
- }
- Subject subject = lc.getSubject();
+ Set<Principal> principals = new HashSet<>();
+ // Create a connection principal to track the remoting connection associated with this subject
+ principals.add(new RemotingConnectionPrincipal(remotingConnection));
+
+ if (password == null) {
+ // Replicate anonymous guest user
+ principals.add(new UserPrincipal(ANONYMOUS_USERNAME));
+ principals.add(new RolePrincipal(ANONYMOUS_USERNAME));
+
+ LOG.finer("Anonymous user authenticated: " + MQTTBrokerService.connectionToString(remotingConnection));
+ } else {
+ String realm = null;
+
+ try {
+ // TODO: Add support for bearer token authentication https://github.com/openremote/openremote/issues/2534
+ // Login service user
+ if (user != null) {
+ int delimIndex = user.indexOf(':');
+ if (delimIndex > 0) {
+ realm = user.substring(0, delimIndex);
+ user = user.substring(delimIndex + 1);
+ }
+ }
+
+ if (realm == null) {
+ LOG.info("Invalid user format: " + user);
+ return null;
+ }
+
+ OIDCTokenResponse oidcTokenResponse = identityService.authenticate(realm, user, password).get(
+ TOKEN_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
+ TokenPrincipal tokenPrincipal = identityService.verify(realm, oidcTokenResponse.getToken());
+ UserPrincipal userPrincipal = new UserPrincipal(tokenPrincipal.getName());
+ principals.add(tokenPrincipal);
+ principals.add(userPrincipal);
+ } catch (InterruptedException | TimeoutException | ExecutionException | AuthenticationException e) {
+ Throwable cause = (e instanceof ExecutionException) ? e.getCause() : e;
+ LOG.info("Failed to authenticate user: realm=" + realm + ", username=" + user + ", exception=" + cause);
+ return null;
+ }
+ }
- if (subject != null) {
- // Set subject here so any code that calls this method behaves like a normal ActiveMQ SecurityStoreImpl::authenticate call
- remotingConnection.setSubject(subject);
- subject.getPrincipals().add(new RemotingConnectionPrincipal(remotingConnection));
- }
+ Subject subject = new Subject(true, principals, Set.of(), Set.of());
+ // Set subject here so any code that calls this method behaves like a normal ActiveMQ SecurityStoreImpl::authenticate call
+ remotingConnection.setSubject(subject);
- return subject;
- } finally {
- if (thisLoader != currentLoader) {
- Thread.currentThread().setContextClassLoader(currentLoader);
- }
- }
+ return subject;
}
@Override
@@ -168,7 +157,7 @@ public class ActiveMQORSecurityManager extends ActiveMQJAASSecurityManager {
return false;
}
- KeycloakSecurityContext securityContext = KeycloakIdentityProvider.getSecurityContext(subject);
+ TokenPrincipal tokenPrincipal = IdentityProvider.getTokenPrincipal(subject);
String topicClientID = MQTTHandler.topicClientID(topic);
if (topicClientID == null) {
@@ -194,9 +183,9 @@ public class ActiveMQORSecurityManager extends ActiveMQJAASSecurityManager {
boolean result;
if (isWrite) {
- result = handler.checkCanPublish(connection, securityContext, topic);
+ result = handler.checkCanPublish(connection, tokenPrincipal, topic);
} else {
- result = handler.checkCanSubscribe(connection, securityContext, topic);
+ result = handler.checkCanSubscribe(connection, tokenPrincipal, topic);
}
if (result) {
LOG.finest("Handler '" + handler.getName() + "' has authorised " + (isWrite ? "pub" : "sub") + ": topic=" + topic + ", " + connectionToString(connection));
@@ -211,4 +200,13 @@ public class ActiveMQORSecurityManager extends ActiveMQJAASSecurityManager {
return false;
}
+ @Override
+ public boolean validateUser(String user, String password) {
+ throw new UnsupportedOperationException("Invoke validateUser(String, String, RemotingConnection, String) instead");
+ }
+
+ @Override
+ public boolean validateUserAndRole(String user, String password, Set<Role> roles, CheckType checkType) {
+ throw new UnsupportedOperationException("Invoke validateUserAndRole(String, String, Set<Role>, CheckType, String, RemotingConnection, String) instead");
+ }
}
diff --git a/manager/src/main/java/org/openremote/manager/mqtt/ConnectionMonitorHandler.java b/manager/src/main/java/org/openremote/manager/mqtt/ConnectionMonitorHandler.java
index 0780d5413..af07af56d 100644
--- a/manager/src/main/java/org/openremote/manager/mqtt/ConnectionMonitorHandler.java
+++ b/manager/src/main/java/org/openremote/manager/mqtt/ConnectionMonitorHandler.java
@@ -23,10 +23,10 @@ import io.netty.buffer.ByteBuf;
import org.apache.activemq.artemis.core.config.Configuration;
import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection;
import org.apache.camel.builder.RouteBuilder;
-import org.keycloak.KeycloakSecurityContext;
import org.openremote.container.message.MessageBrokerService;
import org.openremote.container.persistence.PersistenceService;
-import org.openremote.container.security.keycloak.KeycloakIdentityProvider;
+import org.openremote.container.security.AuthContext;
+import org.openremote.container.security.IdentityProvider;
import org.openremote.manager.asset.AssetProcessingService;
import org.openremote.manager.asset.AssetStorageService;
import org.openremote.manager.gateway.GatewayService;
@@ -59,6 +59,7 @@ import java.util.stream.Collectors;
import static org.openremote.container.persistence.PersistenceService.PERSISTENCE_TOPIC;
import static org.openremote.container.persistence.PersistenceService.isPersistenceEventForEntityType;
import static org.openremote.manager.gateway.GatewayService.isNotForGateway;
+import static org.openremote.manager.mqtt.MQTTBrokerService.connectionToString;
import static org.openremote.model.syslog.SyslogCategory.API;
import static org.openremote.model.value.MetaItemType.USER_CONNECTED;
@@ -220,12 +221,12 @@ public class ConnectionMonitorHandler extends MQTTHandler {
}
@Override
- public boolean canSubscribe(RemotingConnection connection, KeycloakSecurityContext securityContext, Topic topic) {
+ public boolean canSubscribe(RemotingConnection connection, AuthContext authContext, Topic topic) {
return false;
}
@Override
- public boolean canPublish(RemotingConnection connection, KeycloakSecurityContext securityContext, Topic topic) {
+ public boolean canPublish(RemotingConnection connection, AuthContext authContext, Topic topic) {
return false;
}
@@ -309,11 +310,11 @@ public class ConnectionMonitorHandler extends MQTTHandler {
}
protected Pair<String, Set<AttributeRef>> getUserIDAndAttributeRefs(RemotingConnection connection) {
- String userID = KeycloakIdentityProvider.getSubjectId(connection.getSubject());
+ String userID = IdentityProvider.getSubjectId(connection.getSubject());
if (userID == null) {
if (LOG.isLoggable(Level.FINEST)) {
- LOG.finest("Anonymous connection so cannot determine userID: " + mqttBrokerService.connectionToString(connection));
+ LOG.finest("Anonymous connection so cannot determine userID: " + connectionToString(connection));
}
return null;
}
diff --git a/manager/src/main/java/org/openremote/manager/mqtt/DefaultMQTTHandler.java b/manager/src/main/java/org/openremote/manager/mqtt/DefaultMQTTHandler.java
index 18fcc7a8e..43c25ef25 100644
--- a/manager/src/main/java/org/openremote/manager/mqtt/DefaultMQTTHandler.java
+++ b/manager/src/main/java/org/openremote/manager/mqtt/DefaultMQTTHandler.java
@@ -26,7 +26,6 @@ import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.mqtt.MqttQoS;
import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection;
import org.apache.activemq.artemis.utils.collections.ConcurrentHashSet;
-import org.keycloak.KeycloakSecurityContext;
import org.openremote.container.security.AuthContext;
import org.openremote.manager.event.ClientEventService;
import org.openremote.model.PersistenceEvent;
@@ -132,17 +131,15 @@ public class DefaultMQTTHandler extends MQTTHandler {
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
- public boolean canSubscribe(RemotingConnection connection, KeycloakSecurityContext securityContext, Topic topic) {
+ public boolean canSubscribe(RemotingConnection connection, AuthContext authContext, Topic topic) {
if (!isKeycloak) {
LOG.finest("Identity provider is not keycloak");
return false;
}
- AuthContext authContext = getAuthContextFromSecurityContext(securityContext);
-
if (authContext == null) {
- LOG.finest("Anonymous connection not supported: topic=" + topic + ", " + mqttBrokerService.connectionToString(connection));
+ LOG.finest("Anonymous connection not supported: topic=" + topic + ", " + connectionToString(connection));
return false;
}
@@ -156,7 +153,7 @@ public class DefaultMQTTHandler extends MQTTHandler {
if (isAssetTopic) {
if (topic.getTokens().length < 4 || topic.getTokens().length > 5) {
- LOG.finest("Asset subscribe token count should be 4 or 5: topic=" + topic + ", " + mqttBrokerService.connectionToString(connection));
+ LOG.finest("Asset subscribe token count should be 4 or 5: topic=" + topic + ", " + connectionToString(connection));
return false;
}
if (topic.getTokens().length == 4) {
@@ -234,15 +231,13 @@ public class DefaultMQTTHandler extends MQTTHandler {
// We make heavy use of authorisation caching as clients can hit this a lot and it is currently quite slow with DB calls
@Override
- public boolean canPublish(RemotingConnection connection, KeycloakSecurityContext securityContext, Topic topic) {
+ public boolean canPublish(RemotingConnection connection, AuthContext authContext, Topic topic) {
if (!isKeycloak) {
LOG.fine("Identity provider is not keycloak");
return false;
}
- AuthContext authContext = getAuthContextFromSecurityContext(securityContext);
-
if (authContext == null) {
LOG.finer("Anonymous publish not supported: topic=" + topic + ", connection=" + connectionToString(connection));
return false;
diff --git a/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java b/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java
index 882b23e29..6027ae3c2 100644
--- a/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java
+++ b/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java
@@ -38,7 +38,6 @@ import org.apache.activemq.artemis.core.config.Configuration;
import org.apache.activemq.artemis.core.config.MetricsConfiguration;
import org.apache.activemq.artemis.core.config.WildcardConfiguration;
import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl;
-import org.apache.activemq.artemis.core.config.impl.SecurityConfiguration;
import org.apache.activemq.artemis.core.protocol.mqtt.MQTTStateManager;
import org.apache.activemq.artemis.core.protocol.mqtt.MQTTUtil;
import org.apache.activemq.artemis.core.remoting.FailureListener;
@@ -52,15 +51,14 @@ import org.apache.activemq.artemis.core.settings.impl.AddressFullMessagePolicy;
import org.apache.activemq.artemis.core.settings.impl.AddressSettings;
import org.apache.activemq.artemis.core.settings.impl.PageFullMessagePolicy;
import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection;
-import org.apache.activemq.artemis.spi.core.security.jaas.GuestLoginModule;
-import org.apache.activemq.artemis.spi.core.security.jaas.PrincipalConversionLoginModule;
-import org.apache.activemq.artemis.spi.core.security.jaas.RolePrincipal;
-import org.apache.activemq.artemis.spi.core.security.jaas.UserPrincipal;
+import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManager5;
+import org.apache.activemq.artemis.spi.core.security.jaas.*;
import org.apache.camel.builder.RouteBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.keycloak.KeycloakPrincipal;
-import org.keycloak.adapters.jaas.AbstractKeycloakLoginModule;
import org.openremote.container.message.MessageBrokerService;
+import org.openremote.container.security.IdentityProvider;
+import org.openremote.container.security.TokenPrincipal;
import org.openremote.container.security.keycloak.KeycloakIdentityProvider;
import org.openremote.container.timer.TimerService;
import org.openremote.manager.asset.AssetProcessingService;
@@ -69,8 +67,6 @@ import org.openremote.manager.event.ClientEventService;
import org.openremote.manager.security.AuthorisationService;
import org.openremote.manager.security.ManagerIdentityService;
import org.openremote.manager.security.ManagerKeycloakIdentityProvider;
-import org.openremote.manager.security.MultiTenantClientCredentialsGrantsLoginModule;
-import org.openremote.model.Constants;
import org.openremote.model.Container;
import org.openremote.model.ContainerService;
import org.openremote.model.PersistenceEvent;
@@ -94,10 +90,10 @@ import java.util.stream.Collectors;
import static java.lang.System.Logger.Level.*;
import static java.util.stream.StreamSupport.stream;
import static org.openremote.container.persistence.PersistenceService.PERSISTENCE_TOPIC;
+import static org.openremote.container.security.IdentityProvider.getTokenPrincipal;
+import static org.openremote.model.syslog.SyslogCategory.API;
import static org.openremote.model.util.MapAccess.getInteger;
import static org.openremote.model.util.MapAccess.getString;
-import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID;
-import static org.openremote.model.syslog.SyslogCategory.API;
// TODO: Add queue size limiting in canPublish of MQTTHandlers (needs to be done at auth time to allow pub to be rejected)
public class MQTTBrokerService extends RouteBuilder implements ContainerService, ActiveMQServerConnectionPlugin, ActiveMQServerSessionPlugin {
@@ -107,7 +103,6 @@ public class MQTTBrokerService extends RouteBuilder implements ContainerService,
public static final int PRIORITY = MED_PRIORITY;
public static final String MQTT_SERVER_LISTEN_HOST = "MQTT_SERVER_LISTEN_HOST";
public static final String MQTT_SERVER_LISTEN_PORT = "MQTT_SERVER_LISTEN_PORT";
- public static final String ANONYMOUS_USERNAME = "anonymous";
// Allow 5 min durable session but this will not enable retained topics etc. as we delete queues aggressively for now
public static final int DEFAULT_SESSION_EXPIRY_MILLIS = 300000;
protected final WildcardConfiguration wildcardConfiguration = new WildcardConfiguration();
@@ -115,6 +110,7 @@ public class MQTTBrokerService extends RouteBuilder implements ContainerService,
protected AssetStorageService assetStorageService;
protected AuthorisationService authorisationService;
+ protected ManagerIdentityService identityService;
protected ManagerKeycloakIdentityProvider identityProvider;
protected ClientEventService clientEventService;
protected MessageBrokerService messageBrokerService;
@@ -133,7 +129,7 @@ public class MQTTBrokerService extends RouteBuilder implements ContainerService,
protected int port;
protected Configuration serverConfiguration;
protected EmbeddedActiveMQ server;
- protected ActiveMQORSecurityManager securityManager;
+ protected ActiveMQSecurityManager5 securityManager;
protected ServerLocator serverLocator;
protected ClientSessionFactory sessionFactory;
@@ -150,7 +146,7 @@ public class MQTTBrokerService extends RouteBuilder implements ContainerService,
assetStorageService = container.getService(AssetStorageService.class);
authorisationService = container.getService(AuthorisationService.class);
clientEventService = container.getService(ClientEventService.class);
- ManagerIdentityService identityService = container.getService(ManagerIdentityService.class);
+ identityService = container.getService(ManagerIdentityService.class);
messageBrokerService = container.getService(MessageBrokerService.class);
executorService = container.getExecutor();
timerService = container.getService(TimerService.class);
@@ -261,26 +257,13 @@ public class MQTTBrokerService extends RouteBuilder implements ContainerService,
// Start the broker
server = new EmbeddedActiveMQ();
server.setConfiguration(serverConfiguration);
-
- securityManager = new ActiveMQORSecurityManager(authorisationService, this, realm -> identityProvider.getKeycloakDeployment(realm, KEYCLOAK_CLIENT_ID), "", new SecurityConfiguration() {
- @Override
- public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
- return new AppConfigurationEntry[]{
- new AppConfigurationEntry(GuestLoginModule.class.getName(), AppConfigurationEntry.LoginModuleControlFlag.SUFFICIENT, Map.of("debug", "true", "credentialsInvalidate", "true", "org.apache.activemq.jaas.guest.user", ANONYMOUS_USERNAME, "org.apache.activemq.jaas.guest.role", ANONYMOUS_USERNAME)),
- new AppConfigurationEntry(MultiTenantClientCredentialsGrantsLoginModule.class.getName(), AppConfigurationEntry.LoginModuleControlFlag.REQUISITE, Map.of(
- MultiTenantClientCredentialsGrantsLoginModule.INCLUDE_REALM_ROLES_OPTION, "true",
- AbstractKeycloakLoginModule.ROLE_PRINCIPAL_CLASS_OPTION, RolePrincipal.class.getName()
- )),
- new AppConfigurationEntry(PrincipalConversionLoginModule.class.getName(), AppConfigurationEntry.LoginModuleControlFlag.REQUISITE, Map.of(PrincipalConversionLoginModule.PRINCIPAL_CLASS_LIST, KeycloakPrincipal.class.getName()))
- };
- }
- });
+ securityManager = new ActiveMQORSecurityManager(this, executorService, identityService);
server.setSecurityManager(securityManager);
server.start();
LOG.log(DEBUG, "Started MQTT broker");
- // Add notification handler for subscribe/unsubscribe and publish events
+ // Add a notification handler for subscribe/unsubscribe and publish events
server.getActiveMQServer().getManagementService().addNotificationListener(notification -> {
if (notification.getType() == CoreNotificationType.CONSUMER_CREATED || notification.getType() == CoreNotificationType.CONSUMER_CLOSED) {
boolean isSubscribe = notification.getType() == CoreNotificationType.CONSUMER_CREATED;
@@ -483,7 +466,7 @@ public class MQTTBrokerService extends RouteBuilder implements ContainerService,
Subject subject = userConnections.stream().filter(connection -> connection.getSubject() != null).findFirst().map(RemotingConnection::getSubject).orElse(null);
// Only notify handlers if subject is a restricted user
- if (subject != null && KeycloakIdentityProvider.getSecurityContext(subject).getToken().getRealmAccess().isUserInRole(Constants.RESTRICTED_USER_REALM_ROLE)) {
+ if (Optional.ofNullable(getTokenPrincipal(subject)).map(TokenPrincipal::isRestrictedUser).orElse(false)) {
LOG.log(TRACE, "User asset links modified for connected restricted user so passing to handlers to decide what to do: user=" + subject);
// Pass to handlers to decide what to do
userConnections.forEach(connection -> {
@@ -508,7 +491,7 @@ public class MQTTBrokerService extends RouteBuilder implements ContainerService,
return false;
}
Subject subject = connection.getSubject();
- String subjectID = KeycloakIdentityProvider.getSubjectId(subject);
+ String subjectID = IdentityProvider.getSubjectId(subject);
return userID.equals(subjectID);
}).collect(Collectors.toSet());
}
@@ -638,8 +621,13 @@ public class MQTTBrokerService extends RouteBuilder implements ContainerService,
public void authenticateConnection(RemotingConnection connection, String realm, String username, String password) {
if (connection != null) {
connection.setSubject(null); // Clear existing subject
- securityManager.authenticate(realm + ":" + username, password, connection, null);
- notifyConnectionAuthenticated(connection);
+ try {
+ securityManager.authenticate(realm + ":" + username, password, connection, null);
+ notifyConnectionAuthenticated(connection);
+ } catch (NoCacheLoginException e) {
+ LOG.log(INFO, "Failed to authenticate MQTT connection: " + connectionToString(connection));
+ throw new RuntimeException(e);
+ }
}
}
}
diff --git a/manager/src/main/java/org/openremote/manager/mqtt/MQTTHandler.java b/manager/src/main/java/org/openremote/manager/mqtt/MQTTHandler.java
index f816e480e..e8175302c 100644
--- a/manager/src/main/java/org/openremote/manager/mqtt/MQTTHandler.java
+++ b/manager/src/main/java/org/openremote/manager/mqtt/MQTTHandler.java
@@ -32,11 +32,9 @@ import org.apache.activemq.artemis.core.protocol.mqtt.MQTTUtil;
import org.apache.activemq.artemis.core.settings.impl.AddressSettings;
import org.apache.activemq.artemis.reader.MessageUtil;
import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection;
-import org.keycloak.KeycloakSecurityContext;
import org.openremote.container.message.MessageBrokerService;
import org.openremote.container.security.AuthContext;
-import org.openremote.container.security.keycloak.AccessTokenAuthContext;
-import org.openremote.container.security.keycloak.KeycloakIdentityProvider;
+import org.openremote.container.security.IdentityProvider;
import org.openremote.container.timer.TimerService;
import org.openremote.manager.event.ClientEventService;
import org.openremote.manager.security.ManagerIdentityService;
@@ -249,32 +247,32 @@ public abstract class MQTTHandler {
* Checks that authenticated session and topic realm matches the authenticated user and also that topic client ID
* matches the connection client ID.
*/
- public boolean checkCanSubscribe(RemotingConnection connection, KeycloakSecurityContext securityContext, Topic topic) {
- if (securityContext == null) {
+ public boolean checkCanSubscribe(RemotingConnection connection, AuthContext authContext, Topic topic) {
+ if (authContext == null) {
getLogger().finest("Anonymous connection subscriptions not supported by this handler, topic=" + topic + ", " + MQTTBrokerService.connectionToString(connection));
return false;
}
- if (!topicRealmAllowed(securityContext, topic) || !topicClientIdMatches(connection, topic)) {
+ if (!topicRealmAllowed(authContext, topic) || !topicClientIdMatches(connection, topic)) {
getLogger().finest("Topic realm and client ID tokens must match the connection, topic=" + topic + ", " + MQTTBrokerService.connectionToString(connection));
return false;
}
- return canSubscribe(connection, securityContext, topic);
+ return canSubscribe(connection, authContext, topic);
}
/**
* Checks that authenticated sessions and topic realm matches the authenticated user and also that topic client ID
* matches the connection client ID.
*/
- public boolean checkCanPublish(RemotingConnection connection, KeycloakSecurityContext securityContext, Topic topic) {
- if (securityContext == null) {
+ public boolean checkCanPublish(RemotingConnection connection, AuthContext authContext, Topic topic) {
+ if (authContext == null) {
getLogger().finest("Anonymous connection publishes not supported by this handler topic=" + topic + ", " + MQTTBrokerService.connectionToString(connection));
return false;
}
- if (!topicRealmAllowed(securityContext, topic) || !topicClientIdMatches(connection, topic)) {
+ if (!topicRealmAllowed(authContext, topic) || !topicClientIdMatches(connection, topic)) {
getLogger().finest("Topic realm and client ID tokens must match the connection topic=" + topic + ", " + MQTTBrokerService.connectionToString(connection));
return false;
}
- return canPublish(connection, securityContext, topic);
+ return canPublish(connection, authContext, topic);
}
/**
@@ -313,13 +311,13 @@ public abstract class MQTTHandler {
* Called to authorise a subscription if {@link #handlesTopic} returned true; should return true if the subscription
* is allowed otherwise return false.
*/
- public abstract boolean canSubscribe(RemotingConnection connection, KeycloakSecurityContext securityContext, Topic topic);
+ public abstract boolean canSubscribe(RemotingConnection connection, AuthContext authContext, Topic topic);
/**
* Called to authorise a publish if {@link #handlesTopic} returned true; should return true if the publish is
* allowed otherwise return false.
*/
- public abstract boolean canPublish(RemotingConnection connection, KeycloakSecurityContext securityContext, Topic topic);
+ public abstract boolean canPublish(RemotingConnection connection, AuthContext authContext, Topic topic);
/**
* Called to handle subscribe if {@link #canSubscribe} returned true.
@@ -350,8 +348,8 @@ public abstract class MQTTHandler {
return topicTokenIndexToString(topic, 1);
}
- public static boolean topicRealmAllowed(KeycloakSecurityContext securityContext, Topic topic) {
- return securityContext != null && securityContext.getRealm().equals(topicRealm(topic)) || KeycloakIdentityProvider.isSuperUser(securityContext);
+ public static boolean topicRealmAllowed(AuthContext authContext, Topic topic) {
+ return authContext != null && (authContext.getAuthenticatedRealmName().equals(topicRealm(topic)) || authContext.isSuperUser());
}
public static boolean topicClientIdMatches(RemotingConnection connection, Topic topic) {
@@ -370,17 +368,8 @@ public abstract class MQTTHandler {
return connection != null ? connection.getSubject() : null;
}
- protected static KeycloakSecurityContext getSecurityContextFromSubject(Subject subject) {
- return KeycloakIdentityProvider.getSecurityContext(subject);
- }
-
protected static Optional<AuthContext> getAuthContextFromConnection(RemotingConnection connection) {
return Optional.ofNullable(getSubjectFromConnection(connection))
- .map(MQTTHandler::getSecurityContextFromSubject)
- .map(DefaultMQTTHandler::getAuthContextFromSecurityContext);
- }
-
- protected static AuthContext getAuthContextFromSecurityContext(KeycloakSecurityContext securityContext) {
- return securityContext == null ? null : new AccessTokenAuthContext(securityContext.getRealm(), securityContext.getToken());
+ .map(IdentityProvider::getTokenPrincipal);
}
}
diff --git a/manager/src/main/java/org/openremote/manager/mqtt/UserAssetProvisioningMQTTHandler.java b/manager/src/main/java/org/openremote/manager/mqtt/UserAssetProvisioningMQTTHandler.java
index 75be9c815..a9fbf1f36 100644
--- a/manager/src/main/java/org/openremote/manager/mqtt/UserAssetProvisioningMQTTHandler.java
+++ b/manager/src/main/java/org/openremote/manager/mqtt/UserAssetProvisioningMQTTHandler.java
@@ -27,8 +27,8 @@ import org.apache.activemq.artemis.core.config.Configuration;
import org.apache.activemq.artemis.core.settings.impl.AddressSettings;
import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection;
import org.apache.camel.builder.RouteBuilder;
-import org.keycloak.KeycloakSecurityContext;
import org.openremote.container.message.MessageBrokerService;
+import org.openremote.container.security.AuthContext;
import org.openremote.container.timer.TimerService;
import org.openremote.manager.asset.AssetStorageService;
import org.openremote.manager.provisioning.ProvisioningService;
@@ -167,9 +167,9 @@ public class UserAssetProvisioningMQTTHandler extends MQTTHandler {
}
@Override
- public boolean checkCanSubscribe(RemotingConnection connection, KeycloakSecurityContext securityContext, Topic topic) {
+ public boolean checkCanSubscribe(RemotingConnection connection, AuthContext authContext, Topic topic) {
// Skip standard checks
- if (!canSubscribe(connection, securityContext, topic)) {
+ if (!canSubscribe(connection, authContext, topic)) {
getLogger().fine("Cannot subscribe to this topic, topic=" + topic + ", " + MQTTBrokerService.connectionToString(connection));
return false;
}
@@ -177,9 +177,9 @@ public class UserAssetProvisioningMQTTHandler extends MQTTHandler {
}
@Override
- public boolean checkCanPublish(RemotingConnection connection, KeycloakSecurityContext securityContext, Topic topic) {
+ public boolean checkCanPublish(RemotingConnection connection, AuthContext authContext, Topic topic) {
// Skip standard checks
- if (!canPublish(connection, securityContext, topic)) {
+ if (!canPublish(connection, authContext, topic)) {
getLogger().fine("Cannot publish to this topic, topic=" + topic + ", " + MQTTBrokerService.connectionToString(connection));
return false;
}
@@ -199,7 +199,7 @@ public class UserAssetProvisioningMQTTHandler extends MQTTHandler {
}
@Override
- public boolean canSubscribe(RemotingConnection connection, KeycloakSecurityContext securityContext, Topic topic) {
+ public boolean canSubscribe(RemotingConnection connection, AuthContext authContext, Topic topic) {
if (!isKeycloak) {
LOG.fine("Identity provider is not keycloak");
return false;
@@ -243,7 +243,7 @@ public class UserAssetProvisioningMQTTHandler extends MQTTHandler {
}
@Override
- public boolean canPublish(RemotingConnection connection, KeycloakSecurityContext securityContext, Topic topic) {
+ public boolean canPublish(RemotingConnection connection, AuthContext authContext, Topic topic) {
if (!isKeycloak) {
LOG.fine("Identity provider is not keycloak");
return false;
diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerBasicIdentityProvider.java b/manager/src/main/java/org/openremote/manager/security/ManagerBasicIdentityProvider.java
index 625053258..b1e64a958 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerBasicIdentityProvider.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerBasicIdentityProvider.java
@@ -19,18 +19,21 @@
*/
package org.openremote.manager.security;
+import jakarta.security.enterprise.AuthenticationException;
import org.hibernate.Session;
-import org.openremote.model.Container;
import org.openremote.container.security.AuthContext;
+import org.openremote.container.security.TokenPrincipal;
import org.openremote.container.security.basic.BasicIdentityProvider;
import org.openremote.container.security.basic.PasswordStorage;
-import org.openremote.model.event.shared.RealmFilter;
+import org.openremote.model.Container;
import org.openremote.model.query.UserQuery;
import org.openremote.model.security.*;
import org.openremote.model.util.TextUtil;
import java.sql.PreparedStatement;
-import java.util.*;
+import java.util.Objects;
+import java.util.Set;
+import java.util.UUID;
import java.util.logging.Logger;
import static org.openremote.model.Constants.*;
@@ -249,12 +252,6 @@ public class ManagerBasicIdentityProvider extends BasicIdentityProvider implemen
return ManagerIdentityProvider.realmExistsFromDb(persistenceService, realm);
}
- @Override
- public boolean canSubscribeWith(AuthContext auth, RealmFilter<?> filter, ClientRole... requiredRoles) {
- // TODO Doesn't really respect the description of the interface
- return auth.isSuperUser();
- }
-
@Override
public String getFrontendURI() {
return null;
@@ -264,4 +261,9 @@ public class ManagerBasicIdentityProvider extends BasicIdentityProvider implemen
public String toString() {
return getClass().getSimpleName() + "{}";
}
+
+ @Override
+ public TokenPrincipal verify(String realm, String accessToken) throws AuthenticationException {
+ return null;
+ }
}
diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java
index c96764a94..33f0b396b 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java
@@ -98,14 +98,6 @@ public interface ManagerIdentityProvider extends IdentityProvider {
boolean realmExists(String realm);
- /**
- * Superusers can subscribe to all events, regular users must be in the same realm as the filter and any
- * required roles must match. If the authenticated party is a restricted user, this returns <code>false.</code>
- *
- * @return <code>true</code> if the authenticated party can subscribe to events with the given filter.
- */
- boolean canSubscribeWith(AuthContext auth, RealmFilter<?> filter, ClientRole... requiredRoles);
-
/**
* Returns the frontend URL to be used for frontend apps to authenticate
*/
diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityService.java b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityService.java
index 2f779a4a1..f0bf81d61 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityService.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityService.java
@@ -33,7 +33,6 @@ import static org.openremote.model.util.MapAccess.getString;
public class ManagerIdentityService extends IdentityService {
private static final Logger LOG = Logger.getLogger(ManagerIdentityService.class.getName());
-
protected ManagerIdentityProvider identityProvider;
@Override
diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java b/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
index 1bbd61d60..4037464ab 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
@@ -30,11 +30,10 @@ import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriBuilder;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.utils.URIBuilder;
+import org.keycloak.admin.client.resource.*;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.admin.client.resource.UserResource;
-import org.keycloak.admin.client.resource.*;
import org.keycloak.common.enums.SslRequired;
-import org.keycloak.models.UserModel;
import org.keycloak.representations.idm.*;
import org.openremote.container.message.MessageBrokerService;
import org.openremote.container.persistence.PersistenceService;
@@ -52,7 +51,6 @@ import org.openremote.model.PersistenceEvent;
import org.openremote.model.asset.Asset;
import org.openremote.model.auth.OAuthGrant;
import org.openremote.model.auth.OAuthPasswordGrant;
-import org.openremote.model.event.shared.RealmFilter;
import org.openremote.model.gateway.GatewayConnection;
import org.openremote.model.provisioning.ProvisioningConfig;
import org.openremote.model.query.AssetQuery;
@@ -78,9 +76,9 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
+import static org.openremote.model.Constants.*;
import static org.openremote.model.util.MapAccess.getBoolean;
import static org.openremote.model.util.MapAccess.getString;
-import static org.openremote.model.Constants.*;
import static org.openremote.model.util.ValueUtil.convert;
/**
@@ -473,7 +471,7 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
if (realmResource.toRepresentation().getSmtpServer().isEmpty())
throw new IllegalStateException("SMTP server is not configured for realm: " + realm);
realmResource.users().get(userId).executeActionsEmail(
- Collections.singletonList(UserModel.RequiredAction.UPDATE_PASSWORD.toString())
+ Collections.singletonList("UPDATE_PASSWORD")
);
return null;
});
@@ -1220,7 +1218,7 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
@Override
public boolean isRestrictedUser(AuthContext authContext) {
- return authContext != null && authContext.hasRealmRole(RESTRICTED_USER_REALM_ROLE);
+ return authContext != null && authContext.isRestrictedUser();
}
@Override
@@ -1228,38 +1226,6 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
return ManagerIdentityProvider.userInRealmFromDb(persistenceService, userId, realm);
}
- @Override
- public boolean canSubscribeWith(AuthContext auth, RealmFilter<?> filter, ClientRole... requiredRoles) {
- // Superuser can always subscribe
- if (auth.isSuperUser())
- return true;
-
- // Restricted users get nothing
- if (isRestrictedUser(auth))
- return false;
-
- // User must have role
- if (requiredRoles != null) {
- for (ClientRole requiredRole : requiredRoles) {
- if (!auth.hasResourceRole(requiredRole.getValue(), Constants.KEYCLOAK_CLIENT_ID)) {
- return false;
- }
- }
- }
-
- // Ensure filter matches authenticated realm
- if (filter != null) {
- String authenticatedRealm = auth.getAuthenticatedRealmName();
-
- if (TextUtil.isNullOrEmpty(authenticatedRealm))
- return false;
- if (authenticatedRealm.equals(filter.getName()))
- return true;
- }
-
- return false;
- }
-
@Override
public String getFrontendURI() {
return frontendURI;
diff --git a/manager/src/main/java/org/openremote/manager/security/MultiTenantClientCredentialsGrantsLoginModule.java b/manager/src/main/java/org/openremote/manager/security/MultiTenantClientCredentialsGrantsLoginModule.java
deleted file mode 100644
index 264e3b579..000000000
--- a/manager/src/main/java/org/openremote/manager/security/MultiTenantClientCredentialsGrantsLoginModule.java
+++ /dev/null
@@ -1,274 +0,0 @@
-/*
- * Copyright 2022, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.manager.security;
-
-import com.google.common.collect.Sets;
-import org.apache.http.HttpEntity;
-import org.apache.http.HttpResponse;
-import org.apache.http.NameValuePair;
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.entity.UrlEncodedFormEntity;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.message.BasicNameValuePair;
-import org.jboss.logging.Logger;
-import org.keycloak.KeycloakPrincipal;
-import org.keycloak.OAuth2Constants;
-import org.keycloak.adapters.AdapterUtils;
-import org.keycloak.adapters.RefreshableKeycloakSecurityContext;
-import org.keycloak.adapters.jaas.AbstractKeycloakLoginModule;
-import org.keycloak.adapters.rotation.AdapterTokenVerifier;
-import org.keycloak.common.VerificationException;
-import org.keycloak.representations.AccessToken;
-import org.keycloak.representations.AccessTokenResponse;
-import org.keycloak.representations.idm.OAuth2ErrorRepresentation;
-import org.keycloak.util.JsonSerialization;
-
-import javax.security.auth.Subject;
-import javax.security.auth.callback.*;
-import javax.security.auth.login.LoginException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.Serializable;
-import java.net.URI;
-import java.util.*;
-
-/**
- * A version of the Keycloak {@link org.keycloak.adapters.jaas.AbstractKeycloakLoginModule} that supports client
- * credentials grant and lookup of {@link org.keycloak.adapters.KeycloakDeployment} by using
- * the {@link KeycloakDeploymentCallback}. Copied from {@link org.keycloak.adapters.jaas.DirectAccessGrantsLoginModule}
- * which has private members un-fortunately.
- *
- * Also supports including the realm roles (as well as resource roles) by setting the
- * {@link #INCLUDE_REALM_ROLES_OPTION}.
- */
-public class MultiTenantClientCredentialsGrantsLoginModule extends AbstractKeycloakLoginModule {
-
- public static final String INCLUDE_REALM_ROLES_OPTION = "includeRealmRoles";
- public static final String SCOPE_OPTION = "scope";
- private static final Logger log = Logger.getLogger(MultiTenantClientCredentialsGrantsLoginModule.class);
- protected boolean includeRealmRoles;
- protected String scope;
- protected String refreshToken;
-
- @Override
- public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) {
- super.initialize(subject, callbackHandler, sharedState, options);
- this.scope = (String)options.get(SCOPE_OPTION);
-
- // This is used just for logout
- Iterator<MultiTenantClientCredentialsGrantsLoginModule.RefreshTokenHolder> iterator = subject.getPrivateCredentials(MultiTenantClientCredentialsGrantsLoginModule.RefreshTokenHolder.class).iterator();
- if (iterator.hasNext()) {
- refreshToken = iterator.next().refreshToken;
- }
-
- includeRealmRoles = Boolean.parseBoolean((String) options.get(INCLUDE_REALM_ROLES_OPTION));
- }
-
- @Override
- public boolean login() throws LoginException {
- // get username and password and deployment (if not set)
-
- boolean hasDeployment = deployment != null;
- Callback[] callbacks = new Callback[(hasDeployment ? 2 : 3)];
- callbacks[0] = new NameCallback("username");
- callbacks[1] = new PasswordCallback("password", false);
- if (!hasDeployment) {
- callbacks[2] = new KeycloakDeploymentCallback();
- }
-
- try {
- callbackHandler.handle(callbacks);
- String username = ((NameCallback) callbacks[0]).getName();
- char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
- String password = new String(tmpPassword);
- ((PasswordCallback) callbacks[1]).clearPassword();
-
- if (!hasDeployment) {
- deployment = ((KeycloakDeploymentCallback) callbacks[2]).getDeployment();
-
- if (deployment == null) {
- getLogger().warn("Unable to resolve keycloak deployment");
- return false;
- }
- }
-
- Auth auth = doAuth(username, password);
- if (auth != null) {
- this.auth = auth;
- return true;
- } else {
- return false;
- }
- } catch (UnsupportedCallbackException uce) {
- getLogger().warn("Error: " + uce.getCallback().toString()
- + " not available to gather authentication information from the user");
- return false;
- } catch (Exception e) {
- LoginException le = new LoginException(e.toString());
- le.initCause(e);
- throw le;
- }
- }
-
- @Override
- protected Logger getLogger() {
- return log;
- }
-
- @Override
- protected Auth doAuth(String username, String password) throws IOException, VerificationException {
- return clientCredentialsAuth(username, password);
- }
-
- @Override
- public boolean commit() throws LoginException {
- boolean superCommit = super.commit();
-
- // refreshToken will be saved to privateCreds of Subject for now
- if (refreshToken != null) {
- MultiTenantClientCredentialsGrantsLoginModule.RefreshTokenHolder refreshTokenHolder = new MultiTenantClientCredentialsGrantsLoginModule.RefreshTokenHolder();
- refreshTokenHolder.refreshToken = refreshToken;
- subject.getPrivateCredentials().add(refreshTokenHolder);
- }
-
- return superCommit;
- }
-
- protected Auth clientCredentialsAuth(String username, String password) throws IOException, VerificationException {
- String authServerBaseUrl = deployment.getAuthServerBaseUrl();
- HttpPost post = new HttpPost(deployment.getTokenUrl());
- List<NameValuePair> formparams = new ArrayList<NameValuePair>();
- formparams.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.CLIENT_CREDENTIALS));
- formparams.add(new BasicNameValuePair("client_id", username));
- formparams.add(new BasicNameValuePair("client_secret", password));
-
- if (scope != null) {
- formparams.add(new BasicNameValuePair(OAuth2Constants.SCOPE, scope));
- }
-
- //ClientCredentialsProviderUtils.setClientCredentials(deployment, post, formparams);
-
- UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8");
- post.setEntity(form);
-
- HttpClient client = deployment.getClient();
- HttpResponse response = client.execute(post);
- int status = response.getStatusLine().getStatusCode();
- HttpEntity entity = response.getEntity();
- if (status != 200) {
- StringBuilder errorBuilder = new StringBuilder("Login failed. Invalid status: " + status);
- if (entity != null) {
- InputStream is = entity.getContent();
- OAuth2ErrorRepresentation errorRep = JsonSerialization.readValue(is, OAuth2ErrorRepresentation.class);
- errorBuilder.append(", OAuth2 error. Error: " + errorRep.getError())
- .append(", Error description: " + errorRep.getErrorDescription());
- }
- String error = errorBuilder.toString();
- log.warn(error);
- throw new IOException(error);
- }
-
- if (entity == null) {
- throw new IOException("No Entity");
- }
-
- InputStream is = entity.getContent();
- AccessTokenResponse tokenResponse = JsonSerialization.readValue(is, AccessTokenResponse.class);
-
- // refreshToken will be saved to privateCreds of Subject for now
- refreshToken = tokenResponse.getRefreshToken();
-
- AdapterTokenVerifier.VerifiedTokens tokens = AdapterTokenVerifier.verifyTokens(tokenResponse.getToken(), tokenResponse.getIdToken(), deployment);
- return postTokenVerification(tokenResponse.getToken(), tokens.getAccessToken());
- }
-
- @Override
- protected Auth postTokenVerification(String tokenString, AccessToken token) {
- boolean verifyCaller;
- if (deployment.isUseResourceRoleMappings()) {
- verifyCaller = token.isVerifyCaller(deployment.getResourceName());
- } else {
- verifyCaller = token.isVerifyCaller();
- }
- if (verifyCaller) {
- throw new IllegalStateException("VerifyCaller not supported yet in login module");
- }
-
- RefreshableKeycloakSecurityContext skSession = new RefreshableKeycloakSecurityContext(deployment, null, tokenString, token, null, null, null);
- String principalName = AdapterUtils.getPrincipalName(deployment, token);
- final KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = new KeycloakPrincipal<RefreshableKeycloakSecurityContext>(principalName, skSession);
- Set<String> roles;
- roles = AdapterUtils.getRolesFromSecurityContext(skSession);
-
- if (includeRealmRoles && !deployment.isUseResourceRoleMappings()) {
- AccessToken accessToken = skSession.getToken();
- roles = Sets.union(roles, accessToken.getRealmAccess().getRoles());
- }
- return new Auth(principal, roles, tokenString);
- }
-
-
- @Override
- public boolean logout() throws LoginException {
- if (refreshToken != null) {
- try {
- URI logoutUri = deployment.getLogoutUrl().clone().build();
- HttpPost post = new HttpPost(logoutUri);
-
- List<NameValuePair> formparams = new ArrayList<>();
- AdapterUtils.setClientCredentials(deployment, post, formparams);
- formparams.add(new BasicNameValuePair(OAuth2Constants.REFRESH_TOKEN, refreshToken));
-
- UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8");
- post.setEntity(form);
-
- HttpClient client = deployment.getClient();
- HttpResponse response = client.execute(post);
- int status = response.getStatusLine().getStatusCode();
- HttpEntity entity = response.getEntity();
- if (status != 204) {
- StringBuilder errorBuilder = new StringBuilder("Logout of refreshToken failed. Invalid status: " + status);
- if (entity != null) {
- InputStream is = entity.getContent();
- if (status == 400) {
- OAuth2ErrorRepresentation errorRep = JsonSerialization.readValue(is, OAuth2ErrorRepresentation.class);
- errorBuilder.append(", OAuth2 error. Error: " + errorRep.getError())
- .append(", Error description: " + errorRep.getErrorDescription());
-
- } else {
- if (is != null) is.close();
- }
- }
-
- // Should do something better than warn if logout failed? Perhaps update of refresh tokens on existing subject might be supported too...
- log.warn(errorBuilder.toString());
- }
- } catch (IOException ioe) {
- log.warn(ioe);
- }
- }
-
- return super.logout();
- }
-
- private static class RefreshTokenHolder implements Serializable {
- private String refreshToken;
- }
-}
diff --git a/manager/src/main/java/org/openremote/manager/security/MultiTenantJaasCallbackHandler.java b/manager/src/main/java/org/openremote/manager/security/MultiTenantJaasCallbackHandler.java
deleted file mode 100644
index 774bd89b4..000000000
--- a/manager/src/main/java/org/openremote/manager/security/MultiTenantJaasCallbackHandler.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright 2022, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.manager.security;
-
-import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection;
-import org.apache.activemq.artemis.spi.core.security.jaas.CertificateCallback;
-import org.apache.activemq.artemis.spi.core.security.jaas.JaasCallbackHandler;
-import org.apache.activemq.artemis.spi.core.security.jaas.PrincipalsCallback;
-import org.keycloak.adapters.KeycloakDeployment;
-
-import javax.security.auth.Subject;
-import javax.security.auth.callback.*;
-import javax.security.auth.kerberos.KerberosPrincipal;
-import java.io.IOException;
-import java.security.Principal;
-import java.util.Set;
-import java.util.function.Function;
-
-import static org.apache.activemq.artemis.utils.CertificateUtil.getCertsFromConnection;
-import static org.apache.activemq.artemis.utils.CertificateUtil.getPeerPrincipalFromConnection;
-
-/**
- * A version of {@link JaasCallbackHandler} that supports multi-tenancy by introducing support for
- * {@link KeycloakDeploymentCallback}. Unfortunately the fields are private so had to copy most of the code below.
- */
-public class MultiTenantJaasCallbackHandler implements CallbackHandler {
-
- protected final String username;
- protected final String password;
- final RemotingConnection remotingConnection;
- protected final String realm;
- protected final Function<String, KeycloakDeployment> deploymentResolver;
-
- public MultiTenantJaasCallbackHandler(Function<String, KeycloakDeployment> deploymentResolver, String realm, String username, String password, RemotingConnection remotingConnection) {
- this.username = username;
- this.password = password;
- this.remotingConnection = remotingConnection;
- this.realm = realm;
- this.deploymentResolver = deploymentResolver;
- }
-
- @Override
- public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
- for (Callback callback : callbacks) {
- if (callback instanceof PasswordCallback) {
- PasswordCallback passwordCallback = (PasswordCallback) callback;
- if (password == null) {
- passwordCallback.setPassword(null);
- } else {
- passwordCallback.setPassword(password.toCharArray());
- }
- } else if (callback instanceof NameCallback) {
- NameCallback nameCallback = (NameCallback) callback;
- if (username == null) {
- nameCallback.setName(null);
- } else {
- nameCallback.setName(username);
- }
- } else if (callback instanceof CertificateCallback) {
- CertificateCallback certCallback = (CertificateCallback) callback;
-
- certCallback.setCertificates(getCertsFromConnection(remotingConnection));
- } else if (callback instanceof PrincipalsCallback) {
- PrincipalsCallback principalsCallback = (PrincipalsCallback) callback;
-
- Subject peerSubject = remotingConnection.getSubject();
- if (peerSubject != null) {
- for (KerberosPrincipal principal : peerSubject.getPrivateCredentials(KerberosPrincipal.class)) {
- principalsCallback.setPeerPrincipals(new Principal[]{principal});
- return;
- }
- Set<Principal> principals = peerSubject.getPrincipals();
- if (principals.size() > 0) {
- principalsCallback.setPeerPrincipals(principals.toArray(new Principal[0]));
- return;
- }
- }
-
- Principal peerPrincipalFromConnection = getPeerPrincipalFromConnection(remotingConnection);
- if (peerPrincipalFromConnection != null) {
- principalsCallback.setPeerPrincipals(new Principal[]{peerPrincipalFromConnection});
- }
- } else if (callback instanceof KeycloakDeploymentCallback keycloakDeploymentCallback) {
- keycloakDeploymentCallback.setDeployment(deploymentResolver.apply(realm));
- } else {
- throw new UnsupportedCallbackException(callback);
- }
- }
- }
-}
diff --git a/manager/src/main/java/org/openremote/manager/security/ORLoginModule.java b/manager/src/main/java/org/openremote/manager/security/ORLoginModule.java
deleted file mode 100644
index a942acbe9..000000000
--- a/manager/src/main/java/org/openremote/manager/security/ORLoginModule.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright 2022, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.manager.security;
-
-import javax.security.auth.Subject;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.login.LoginException;
-import javax.security.auth.spi.LoginModule;
-import java.util.Map;
-
-/**
- * A {@link LoginModule} specific to OpenRemote
- */
-public class ORLoginModule implements LoginModule {
-
-
-
- @Override
- public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) {
-
- }
-
- @Override
- public boolean login() throws LoginException {
- return false;
- }
-
- @Override
- public boolean commit() throws LoginException {
- return false;
- }
-
- @Override
- public boolean abort() throws LoginException {
- return false;
- }
-
- @Override
- public boolean logout() throws LoginException {
- return false;
- }
-}
diff --git a/manager/src/main/java/org/openremote/manager/web/ManagerWebService.java b/manager/src/main/java/org/openremote/manager/web/ManagerWebService.java
index 9c1a867ae..511c3d627 100644
--- a/manager/src/main/java/org/openremote/manager/web/ManagerWebService.java
+++ b/manager/src/main/java/org/openremote/manager/web/ManagerWebService.java
@@ -109,7 +109,7 @@ public class ManagerWebService extends WebService {
initialised = true;
// Configure the JAX-RS Manager API including resources added at startup
- List<Object> singletons = Stream.of(getStandardProviders(devMode, 0), apiSingletons)
+ List<Object> singletons = Stream.of(getStandardProviders(devMode), apiSingletons)
.flatMap(Collection::stream)
.toList();
Application application = new WebApplication(container, apiClasses, singletons);
@@ -139,7 +139,7 @@ public class ManagerWebService extends WebService {
}
// Deploy static app files unsecured
- deployFileServlet("/", "App Files", resourceSources.toArray(ResourceSource[]::new), null, null);
+ deployFileServlet("/", "App Files", resourceSources.toArray(ResourceSource[]::new), null, null, null);
}
protected Object getOpenApiResource() {
diff --git a/model/src/main/java/org/openremote/model/http/RequestParams.java b/model/src/main/java/org/openremote/model/http/RequestParams.java
index 49832d459..27eefda04 100644
--- a/model/src/main/java/org/openremote/model/http/RequestParams.java
+++ b/model/src/main/java/org/openremote/model/http/RequestParams.java
@@ -19,6 +19,7 @@
*/
package org.openremote.model.http;
+import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
@@ -72,4 +73,8 @@ public class RequestParams {
return this.uriInfo.getBaseUriBuilder().scheme(scheme).host(host).port(port);
}
+
+ public static String getBearerAuth(@NotNull String authorizationHeader) {
+ return authorizationHeader.isEmpty() || authorizationHeader.charAt(0) != 'B' ? authorizationHeader : authorizationHeader.substring(BEARER_AUTH_PREFIX.length()).trim();
+ }
}
diff --git a/project.gradle b/project.gradle
index 0bc8f860b..455648234 100644
--- a/project.gradle
+++ b/project.gradle
@@ -22,11 +22,6 @@ import org.jetbrains.gradle.ext.JUnit
configurations.all {
resolutionStrategy {
- // Force using a newer version to prevent vulnerabilities of the Bouncy Castle transitive dependencies of Keycloak
- force "org.bouncycastle:bcpkix-jdk18on:$bouncyCastleVersion"
- force "org.bouncycastle:bcprov-jdk18on:$bouncyCastleVersion"
- force "org.bouncycastle:bcutil-jdk18on:$bouncyCastleVersion"
-
//failOnVersionConflict()
// This has been replaced with eclipse angus implementation
diff --git a/test/build.gradle b/test/build.gradle
index 4532d142b..5912d32fd 100644
--- a/test/build.gradle
+++ b/test/build.gradle
@@ -39,6 +39,12 @@ dependencies {
testImplementation "com.github.moquette-io:moquette:$moquetteVersion"
testImplementation "com.hivemq:hivemq-mqtt-client:$hiveMQClientVersion"
+
+ testImplementation "io.grpc:grpc-netty-shaded:$grpcVersion"
+ testImplementation "io.grpc:grpc-protobuf:$grpcVersion"
+ testImplementation "io.grpc:grpc-stub:$grpcVersion"
+
+ testImplementation "org.bouncycastle:bcpkix-jdk18on:$bouncyCastleVersion"
}
tasks.withType(Test) {
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy
index 796af6665..f7bc80888 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy
@@ -1,7 +1,6 @@
package org.openremote.test.assets
-import org.keycloak.adapters.rotation.AdapterTokenVerifier
-import org.openremote.container.security.keycloak.AccessTokenAuthContext
+import jakarta.ws.rs.WebApplicationException
import org.openremote.container.timer.TimerService
import org.openremote.manager.security.ManagerIdentityService
import org.openremote.manager.setup.SetupService
@@ -12,12 +11,10 @@ import org.openremote.setup.integration.ManagerTestSetup
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
-import jakarta.ws.rs.WebApplicationException
-
-import static org.openremote.model.util.MapAccess.getString
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.Constants.*
+import static org.openremote.model.util.MapAccess.getString
class AssetUserLinkingTest extends Specification implements ManagerContainerTrait {
@@ -44,16 +41,13 @@ class AssetUserLinkingTest extends Specification implements ManagerContainerTrai
and: "user access tokens"
def testUserAccessToken = authenticate(container, MASTER_REALM, KEYCLOAK_CLIENT_ID, "testuser1", "testuser1")
- def accessToken = AdapterTokenVerifier.verifyToken(testUserAccessToken, keycloakTestSetup.getKeycloakProvider().getKeycloakDeployment(MASTER_REALM, KEYCLOAK_CLIENT_ID))
- def testUser1Token = new AccessTokenAuthContext(MASTER_REALM, accessToken)
+ def testUser1Token = identityService.verify(MASTER_REALM, testUserAccessToken)
testUserAccessToken = authenticate(container, keycloakTestSetup.realmBuilding.name, KEYCLOAK_CLIENT_ID, "testuser2", "testuser2")
- accessToken = AdapterTokenVerifier.verifyToken(testUserAccessToken, keycloakTestSetup.getKeycloakProvider().getKeycloakDeployment(keycloakTestSetup.realmBuilding.name, KEYCLOAK_CLIENT_ID))
- def testUser2Token = new AccessTokenAuthContext(keycloakTestSetup.realmBuilding.name, accessToken)
+ def testUser2Token = identityService.verify(keycloakTestSetup.realmBuilding.name, testUserAccessToken)
testUserAccessToken = authenticate(container, keycloakTestSetup.realmBuilding.name, KEYCLOAK_CLIENT_ID, "testuser3", "testuser3")
- accessToken = AdapterTokenVerifier.verifyToken(testUserAccessToken, keycloakTestSetup.getKeycloakProvider().getKeycloakDeployment(keycloakTestSetup.realmBuilding.name, KEYCLOAK_CLIENT_ID))
- def testUser3Token = new AccessTokenAuthContext(keycloakTestSetup.realmBuilding.name, accessToken)
+ def testUser3Token = identityService.verify(keycloakTestSetup.realmBuilding.name, testUserAccessToken)
expect: "some users to be restricted"
!identityService.getIdentityProvider().isRestrictedUser(testUser1Token)
diff --git a/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientTest.groovy
index 7102cc118..e66631a9d 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientTest.groovy
@@ -32,24 +32,19 @@ import org.openremote.manager.asset.AssetStorageService
import org.openremote.manager.setup.SetupService
import org.openremote.model.asset.Asset
import org.openremote.model.asset.AssetEvent
-import org.openremote.model.asset.impl.BuildingAsset
-import org.openremote.model.attribute.Attribute
-import org.openremote.model.attribute.MetaItem
-import org.openremote.model.event.shared.SharedEvent
-import org.openremote.model.geo.GeoJSONPoint
-import org.openremote.model.value.MetaItemType
-import org.openremote.model.value.ValueType
-import org.openremote.setup.integration.KeycloakTestSetup
-import org.openremote.setup.integration.ManagerTestSetup
import org.openremote.model.asset.AssetFilter
import org.openremote.model.asset.agent.ConnectionStatus
+import org.openremote.model.asset.impl.BuildingAsset
import org.openremote.model.attribute.Attribute
import org.openremote.model.attribute.AttributeEvent
+import org.openremote.model.attribute.MetaItem
import org.openremote.model.auth.OAuthPasswordGrant
import org.openremote.model.event.TriggeredEventSubscription
import org.openremote.model.event.shared.EventSubscription
import org.openremote.model.event.shared.SharedEvent
+import org.openremote.model.geo.GeoJSONPoint
import org.openremote.model.util.ValueUtil
+import org.openremote.model.value.MetaItemType
import org.openremote.model.value.ValueType
import org.openremote.setup.integration.KeycloakTestSetup
import org.openremote.setup.integration.ManagerTestSetup
@@ -171,7 +166,7 @@ class WebsocketClientTest extends Specification implements ManagerContainerTrait
receivedMessages2.add(messageFromString(it))
})
client2.addConnectionStatusConsumer({
- getLOG().info("Client1 status change: $it")
+ getLOG().info("Client2 status change: $it")
connectionStatus2 = it
})
client3.addMessageConsumer({