100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Updated to latest keycloak and undertow versions (#1247)
Rich Turner1df81e1045be
diff --git a/container/build.gradle b/container/build.gradleindex d1fe82c9b..47363a11c 100644--- a/container/build.gradle+++ b/container/build.gradle@@ -29,7 +29,8 @@ dependencies {api "org.keycloak:keycloak-client-registration-api:$keycloakVersion"api "org.keycloak:keycloak-adapter-core:$keycloakVersion"- api "org.keycloak:keycloak-admin-client-jakarta:$keycloakVersion"+ api "org.keycloak:keycloak-policy-enforcer:$keycloakVersion"+ api "org.keycloak:keycloak-admin-client:$keycloakVersion"api "org.postgresql:postgresql:$postgresJdbcVersion"api "org.flywaydb:flyway-core:$flywaydbVersion"diff --git a/docker-compose.yml b/docker-compose.ymlindex eedfea3f1..9549050f1 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -37,6 +37,7 @@ services:postgresql:restart: alwaysimage: openremote/postgresql:${POSTGRESQL_VERSION:-latest}+ shm_size: 128mbvolumes:- postgresql-data:/var/lib/postgresql/data- manager-data:/storage@@ -63,7 +64,7 @@ services:keycloak:condition: service_healthyports:- - "127.0.0.1:8405:8404" # Localhost metrics access+ - "127.0.0.1:8405:8405" # Localhost metrics accessenvironment:OR_SETUP_TYPE:OR_ADMIN_PASSWORD:diff --git a/gradle.properties b/gradle.propertiesindex cb4aa2fcb..c88282312 100644--- a/gradle.properties+++ b/gradle.properties@@ -7,10 +7,10 @@ javaxELAPIVersion = 5.0.1javaxELVersion = 4.0.2slf4jVersion = 2.0.6guavaVersion = 31.1-jre-undertowVersion = 2.3.4.Final+undertowVersion = 2.3.10.FinalresteasyVersion = 6.2.7.FinaljbossLoggingAnnotationsVersion = 2.0.2.Final-keycloakVersion = 18.0.2+keycloakVersion = 23.0.6classgraphVersion=4.8.149jacksonVersion = 2.16.0groovyVersion = 3.0.10diff --git a/manager/src/main/java/org/openremote/manager/security/MultiTenantClientCredentialsGrantsLoginModule.java b/manager/src/main/java/org/openremote/manager/security/MultiTenantClientCredentialsGrantsLoginModule.javaindex f24c2d2de..d6b40ce69 100644--- a/manager/src/main/java/org/openremote/manager/security/MultiTenantClientCredentialsGrantsLoginModule.java+++ b/manager/src/main/java/org/openremote/manager/security/MultiTenantClientCredentialsGrantsLoginModule.java@@ -32,10 +32,10 @@ import org.keycloak.KeycloakPrincipal;import org.keycloak.OAuth2Constants;import org.keycloak.adapters.AdapterUtils;import org.keycloak.adapters.RefreshableKeycloakSecurityContext;-import org.keycloak.adapters.authentication.ClientCredentialsProviderUtils;import org.keycloak.adapters.jaas.AbstractKeycloakLoginModule;import org.keycloak.adapters.rotation.AdapterTokenVerifier;import org.keycloak.common.VerificationException;+import org.keycloak.protocol.oidc.client.authentication.ClientCredentialsProviderUtils;import org.keycloak.representations.AccessToken;import org.keycloak.representations.AccessTokenResponse;import org.keycloak.representations.idm.OAuth2ErrorRepresentation;@@ -234,7 +234,7 @@ public class MultiTenantClientCredentialsGrantsLoginModule extends AbstractKeyclHttpPost post = new HttpPost(logoutUri);List<NameValuePair> formparams = new ArrayList<>();- ClientCredentialsProviderUtils.setClientCredentials(deployment, post, formparams);+ AdapterUtils.setClientCredentials(deployment, post, formparams);formparams.add(new BasicNameValuePair(OAuth2Constants.REFRESH_TOKEN, refreshToken));UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8");diff --git a/profile/demo.yml b/profile/demo.ymlindex a0fb03600..5f7f0daeb 100644--- a/profile/demo.yml+++ b/profile/demo.yml@@ -60,6 +60,7 @@ services:postgresql:restart: alwaysimage: openremote/postgresql:${POSTGRESQL_VERSION:-latest}+ shm_size: 128mbvolumes:- postgresql-data:/var/lib/postgresql/data- manager-data:/storage@@ -86,7 +87,7 @@ services:keycloak:condition: service_healthyports:- - "127.0.0.1:8405:8404" # Localhost metrics access+ - "127.0.0.1:8405:8405" # Localhost metrics accessenvironment:# Set this variable `demo` to auto provision demo assets etc.OR_SETUP_TYPE: ${OR_SETUP_TYPE:-demo}diff --git a/profile/deploy.yml b/profile/deploy.ymlindex 2da8a9382..0d490a9a4 100644--- a/profile/deploy.yml+++ b/profile/deploy.yml@@ -126,7 +126,7 @@ services:# - "8080:8080" # Web server port# - "8000:8000" # Remote debugging port - NOT FOR PRODUCTION USE!!!# - "8085:8085" # JMX port - FOR DIAGNOSTICS ONLY!!!- # - "127.0.0.1:8405:8404" # Localhost metrics access+ # - "127.0.0.1:8405:8405" # Localhost metrics accesslogging:options:# Use very little logging for container STDOUT, this is@@ -372,6 +372,8 @@ services:postgresql:image: openremote/postgresql:${POSTGRESQL_VERSION:-latest}restart: always+ # Shared memory should be increased for any reasonable DB size this should be increased further+ shm_size: 128mb# Docker volume for persistent storage of DB; can alternatively map to hostvolumes:# Needs to be available on the same path as the manager for data exports to workdiff --git a/ui/app/manager/src/index.ts b/ui/app/manager/src/index.tsindex e1564a809..832b0242d 100644--- a/ui/app/manager/src/index.ts+++ b/ui/app/manager/src/index.ts@@ -229,15 +229,17 @@ fetch(configURL).then(async (result) => {// Check local storage for set language, otherwise use language set in configmanager.console.retrieveData("LANGUAGE").then((value: string | undefined) => {- manager.language = (value ? value : orAppConfig.realms[manager.displayRealm].language);- }).catch(() => {- if (orAppConfig.realms[manager.displayRealm]){+ if (value) {+ manager.language = value;+ } else if (orAppConfig.realms[manager.displayRealm]) {manager.language = orAppConfig.realms[manager.displayRealm].language- } else if (orAppConfig.realms['default']){+ } else if (orAppConfig.realms['default']) {manager.language = orAppConfig.realms['default'].language} else {manager.language = 'en'}+ }).catch(reason => {+ console.error("Failed to initialise app: " + reason);})// Add config prefix if defined (used in dev)diff --git a/ui/component/core/package.json b/ui/component/core/package.jsonindex 483f08450..c2b7c12e0 100644--- a/ui/component/core/package.json+++ b/ui/component/core/package.json@@ -24,6 +24,7 @@"@openremote/rest": "workspace:*","i18next": "^21.5.3","i18next-http-backend": "^1.3.1",+ "keycloak-js": "^23.0.6","moment": "^2.29.4","platform": "^1.3.6","qs": "^6.8.0",diff --git a/ui/component/core/src/index.ts b/ui/component/core/src/index.tsindex 923b4585a..ac0b25a22 100644--- a/ui/component/core/src/index.ts+++ b/ui/component/core/src/index.ts@@ -9,6 +9,7 @@ import moment from "moment";import {AssetModelUtil, Auth, ConsoleAppConfig, EventProviderType, ManagerConfig, MapType, Role, User, UsernamePassword} from "@openremote/model";import * as Util from "./util";import {createMdiIconSet, createSvgIconSet, IconSets, OrIconSet} from "@openremote/or-icon";+import Keycloak from 'keycloak-js';// Re-exportsexport {Util};@@ -24,25 +25,6 @@ export declare type KeycloakPromise<T> = {error<TResult = never>(onrejected?: ((reason: any) => TResult | KeycloakPromise<TResult>) | undefined | null): Promise<T | TResult>;}-export declare type Keycloak = {- token: string;- refreshToken: string;- tokenParsed: any;- refreshTokenParsed: any;- resourceAccess: any;- onAuthSuccess: () => void;- onAuthError: () => void;- onAuthRefreshSuccess: () => void;- onAuthRefreshError: () => void;- init(options?: any): PromiseLike<boolean>;- login(options?: any): void;- hasRealmRole(role: string): boolean;- logout(options?: any): void;- isTokenExpired(expiry?: number): boolean;- updateToken(expiry?: number): PromiseLike<boolean>;- clearToken(): void;-}-export enum ORError {MANAGER_FAILED_TO_LOAD = "MANAGER_FAILED_TO_LOAD",AUTH_FAILED = "AUTH_FAILED",@@ -244,8 +226,10 @@ export class Manager implements EventProviderFactory {}set language(lang: string) {- i18next.changeLanguage(lang);- this.console.storeData("LANGUAGE", lang);+ if (lang) {+ i18next.changeLanguage(lang);+ this.console.storeData("LANGUAGE", lang);+ }}get displayRealm() {@@ -462,7 +446,7 @@ export class Manager implements EventProviderFactory {// Look for language preference in local storageconst language: string | undefined = !this.console ? undefined : await this.console.retrieveData("LANGUAGE");const initOptions: InitOptions = {- lng: language,+ lng: language || "en",fallbackLng: "en",defaultNS: "app",fallbackNS: "or",@@ -794,8 +778,7 @@ export class Manager implements EventProviderFactory {if (this.console.isMobile) {this.console.storeData("REFRESH_TOKEN", null);}- const options = redirectUrl && redirectUrl !== "" ? {redirectUri: redirectUrl} : null;- this._keycloak.logout(options);+ this._keycloak.logout(redirectUrl && redirectUrl !== "" ? {redirectUri: redirectUrl} : undefined);} else if (this._basicIdentity) {this._basicIdentity = undefined;if (redirectUrl) {@@ -970,7 +953,7 @@ export class Manager implements EventProviderFactory {// By default, using a margin / minimum validity of 2 secondspublic isTokenExpired(margin = 2000): boolean {if(this.isKeycloak()) {- return (this._keycloak!.tokenParsed.exp <= moment().add(margin, "milliseconds").unix());+ return (this._keycloak?.tokenParsed?.exp! <= moment().add(margin, "milliseconds").unix());} else {return !this._basicIdentity?.token; // TODO: Update this to check validity of JWT token manually}@@ -995,7 +978,7 @@ export class Manager implements EventProviderFactory {// If native shell is enabled, we need an offline refresh tokenif (this.console && this.console.isMobile && this.config.auth === Auth.KEYCLOAK) {- if (this._keycloak && this._keycloak.refreshTokenParsed.typ === "Offline") {+ if (this._keycloak && this._keycloak.refreshTokenParsed?.typ === "Offline") {console.debug("Storing offline refresh token");this.console.storeData("REFRESH_TOKEN", this._keycloak!.refreshToken);} else {@@ -1009,31 +992,15 @@ export class Manager implements EventProviderFactory {protected async loadAndInitialiseKeycloak(): Promise<boolean> {try {-- // There's a bug in some Keycloak versions which means the init promise doesn't resolve- // so putting a check in place; wrap keycloak promise in proper ES6 promise- let keycloakPromise: any = null;-- // Load the keycloak JS API- await Util.loadJs(this._config.keycloakUrl + "/js/keycloak.min.js");-- // Should have Keycloak global var now- if (!(window as any).Keycloak) {- console.log("Keycloak global variable not found probably failed to load keycloak or manager doesn't support it");- return false;- }-// Initialise keycloak- this._keycloak = (window as any).Keycloak({+ this._keycloak = new Keycloak({clientId: this._config.clientId,realm: this._config.realm,- url: this._config.keycloakUrl+ url: this._config.keycloakUrl,+});this._keycloak!.onAuthSuccess = () => {- if (keycloakPromise) {- keycloakPromise(true);- }// clear auth reconnect timer after successthis._finishAuthReconnectTimer(true);};@@ -1047,50 +1014,42 @@ export class Manager implements EventProviderFactory {this._setAuthDisconnected(true);}- try {- // Try to use a stored offline refresh token if defined- const offlineToken = await this._getNativeOfflineRefreshToken();-- const authenticated = await this._keycloak!.init({- checkLoginIframe: false, // Doesn't work well with offline tokens or periodic token updates- onLoad: this._config.autoLogin ? "login-required" : "check-sso",- refreshToken: offlineToken- });+ // Try to use a stored offline refresh token if defined+ const offlineToken = await this._getNativeOfflineRefreshToken();- keycloakPromise = null;+ const authenticated = await this._keycloak!.init({+ checkLoginIframe: false, // Doesn't work well with offline tokens or periodic token updates+ onLoad: this._config.autoLogin ? "login-required" : "check-sso",+ refreshToken: offlineToken+ });- if (authenticated) {+ if (authenticated) {- this._name = this._keycloak!.tokenParsed.name;- this._username = this._keycloak!.tokenParsed.preferred_username;+ this._name = this._keycloak.tokenParsed?.name;+ this._username = this._keycloak.tokenParsed?.preferred_username;- // Update the access token every 10s (note keycloak will only update if expiring within configured- // time period.- if (this._keycloakUpdateTokenInterval) {- clearInterval(this._keycloakUpdateTokenInterval);- delete this._keycloakUpdateTokenInterval;- }- this._keycloakUpdateTokenInterval = window.setInterval(() => {- // only try to update token when online, otherwise the reconnect logic (this._attemptReconnect()) will try this- if(!this._authDisconnected) {- this.updateKeycloakAccessToken().catch(() => {- console.error("Could not update keycloak access token during regular interval.");- });- }- }, 10000);- this._onAuthenticated();+ // Update the access token every 10s (note keycloak will only update if expiring within configured+ // time period.+ if (this._keycloakUpdateTokenInterval) {+ clearInterval(this._keycloakUpdateTokenInterval);+ delete this._keycloakUpdateTokenInterval;}- this._setAuthenticated(authenticated);- return true;- } catch (e) {- console.error(e);- keycloakPromise = null;- this._setAuthenticated(false);- return false;+ this._keycloakUpdateTokenInterval = window.setInterval(() => {+ // only try to update token when online, otherwise the reconnect logic (this._attemptReconnect()) will try this+ if(!this._authDisconnected) {+ this.updateKeycloakAccessToken().catch(() => {+ console.error("Could not update keycloak access token during regular interval.");+ });+ }+ }, 10000);+ this._onAuthenticated();}+ this._setAuthenticated(authenticated);+ return true;} catch (error) {+ this._setAuthenticated(false);this._setError(ORError.AUTH_FAILED);- console.error("Failed to load Keycloak");+ console.error("Failed to initialise Keycloak: " + error);return false;}}diff --git a/yarn.lock b/yarn.lockindex 8d4ddf9fe..4b287aa94 100644--- a/yarn.lock+++ b/yarn.lock@@ -2295,6 +2295,7 @@ __metadata:"@types/qs": "npm:^6.9.7"i18next: "npm:^21.5.3"i18next-http-backend: "npm:^1.3.1"+ keycloak-js: "npm:^23.0.6"moment: "npm:^2.29.4"platform: "npm:^1.3.6"qs: "npm:^6.8.0"@@ -3951,6 +3952,13 @@ __metadata:languageName: nodelinkType: hard+"base64-js@npm:^1.5.1":+ version: 1.5.1+ resolution: "base64-js@npm:1.5.1"+ checksum: 10c0/f23823513b63173a001030fae4f2dabe283b99a9d324ade3ad3d148e218134676f1ee8568c877cd79ec1c53158dcf2d2ba527a97c606618928ba99dd930102bf+ languageName: node+ linkType: hard+"batch@npm:0.6.1":version: 0.6.1resolution: "batch@npm:0.6.1"@@ -6580,6 +6588,13 @@ __metadata:languageName: nodelinkType: hard+"js-sha256@npm:^0.10.1":+ version: 0.10.1+ resolution: "js-sha256@npm:0.10.1"+ checksum: 10c0/c63119f7c7f8afc24bfa24c1a6b51147c3b562316b6341a375a1cef88569340ec0dbf2cda429ecf472cabfbae47a0b93a0cb82b8730883de066593c3f816c53b+ languageName: node+ linkType: hard+"js-tokens@npm:^4.0.0":version: 4.0.0resolution: "js-tokens@npm:4.0.0"@@ -6691,6 +6706,13 @@ __metadata:languageName: nodelinkType: hard+"jwt-decode@npm:^4.0.0":+ version: 4.0.0+ resolution: "jwt-decode@npm:4.0.0"+ checksum: 10c0/de75bbf89220746c388cf6a7b71e56080437b77d2edb29bae1c2155048b02c6b8c59a3e5e8d6ccdfd54f0b8bda25226e491a4f1b55ac5f8da04cfbadec4e546c+ languageName: node+ linkType: hard+"kdbush@npm:^3.0.0":version: 3.0.0resolution: "kdbush@npm:3.0.0"@@ -6698,6 +6720,17 @@ __metadata:languageName: nodelinkType: hard+"keycloak-js@npm:^23.0.6":+ version: 23.0.6+ resolution: "keycloak-js@npm:23.0.6"+ dependencies:+ base64-js: "npm:^1.5.1"+ js-sha256: "npm:^0.10.1"+ jwt-decode: "npm:^4.0.0"+ checksum: 10c0/2201d7c8cbd9bf556b212895afc1bf68fa4fed47e8f1ac64f96dbfff56e29d182e89d6729f5097ee41910ea8e6284192735483cd274deeb2da7e41d7164c4af1+ languageName: node+ linkType: hard+"keyv@npm:^4.5.3":version: 4.5.4resolution: "keyv@npm:4.5.4"