Skip to content

armgit / core

Public Imported from GitHub
0

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

Disabled Keycloak status iframe, added refresh/access token periodic checking to or-app-security (iframe and offline tokens are no good), fixed bug in demo auto ventilation rules, reduced database connection timeout to 5 seconds (don't have to wait on startup anymore because of Docker healthcheck)

Christian Bauer9fa4bc6e2f75
diff --git a/client/src/main/webapp/src/manager/or-manager-console-apps/or-manager-console-apps-view.html b/client/src/main/webapp/src/manager/or-manager-console-apps/or-manager-console-apps-view.html
index 3ef87fce9..dcb9af9c3 100644
--- a/client/src/main/webapp/src/manager/or-manager-console-apps/or-manager-console-apps-view.html
+++ b/client/src/main/webapp/src/manager/or-manager-console-apps/or-manager-console-apps-view.html
@@ -85,12 +85,6 @@
this.shadowRoot.host.classList.add("flex", "layout", "vertical");
}
- connectedCallback() {
- super.connectedCallback();
-
- this.showComponent();
- }
-
disconnectedCallback() {
super.disconnectedCallback();
diff --git a/client/src/main/webapp/src/or-app/or-app-security.html b/client/src/main/webapp/src/or-app/or-app-security.html
index 1ece56d43..b1ab1b224 100644
--- a/client/src/main/webapp/src/or-app/or-app-security.html
+++ b/client/src/main/webapp/src/or-app/or-app-security.html
@@ -155,6 +155,13 @@
computed: "computeKeycloak(realm)"
},
+ /**
+ * Periodic access token update interval, checking if the refresh token is still valid.
+ */
+ keycloakUpdateTokenInterval: {
+ type: Number
+ },
+
/**
* Hold credentials when basic authentication is successful to authorize future requests.
*/
@@ -210,13 +217,19 @@
return;
this.set("authenticated", false);
+
+ // Let native shell know about logout
+ if (this.shellNative && this.shellNative.enabled) {
+ this.shellNative.postNativeShellMessage({type: 'logout'});
+ }
+
let logoutUrl = location.protocol + "//" + location.host + location.pathname;
if (this.keycloak) {
-
- // Clear native shell stored tokens
- if (this.shellNative && this.shellNative.enabled) {
- this.shellNative.postNativeShellMessage({type: 'logout'});
+ // Clear refresh token check interval
+ if (this.keycloakUpdateTokenInterval) {
+ clearInterval(this.keycloakUpdateTokenInterval);
+ delete this.keycloakUpdateTokenInterval;
}
// Navigate to start page on logout, drop the hash (also, Keycloak has a bug where it
@@ -290,18 +303,10 @@
if (!this.authenticated) {
onComplete();
} else if (this.keycloak) {
- // Token must be good for X more seconds, should be half of Constants.ACCESS_TOKEN_LIFESPAN_SECONDS
- let minValiditySeconds = 30;
- this.keycloak.updateToken(minValiditySeconds)
- .success((tokenRefreshed) => {
- console.debug("For request authorization, access token was refreshed from auth server: " + tokenRefreshed)
- requestParams.withBearerAuth(this.keycloak.token);
- onComplete();
- })
- .error(() => {
- console.warn("For request authorization, Access token refresh failed, session expired, logging out...");
- this.logout();
- });
+ this.updateKeycloakAccessToken(() => {
+ requestParams.withBearerAuth(this.keycloak.token);
+ onComplete();
+ });
} else {
requestParams.setUsername(this.user);
requestParams.setPassword(this.basicAuthPassword);
@@ -315,12 +320,14 @@
}
serviceUrl = serviceUrl + "?Auth-Realm=" + this.realm;
if (this.keycloak) {
- // TODO Should use keycloak.updateToken()?
- serviceUrl = serviceUrl + "&Authorization=Bearer " + this.keycloak.token;
+ this.updateKeycloakAccessToken(() => {
+ serviceUrl = serviceUrl + "&Authorization=Bearer " + this.keycloak.token;
+ onComplete(serviceUrl);
+ });
} else {
serviceUrl = serviceUrl + "&Authorization=Basic " + window.btoa(this.user + ":" + this.basicAuthPassword);
+ onComplete(serviceUrl);
}
- onComplete(serviceUrl);
}
computeKeycloak(realm) {
@@ -347,69 +354,110 @@
startKeycloakAuthentication() {
console.debug("Keycloak authentication init");
- // Require login and enable invisible login status iframe of Keycloak: This sets a cookie that
- // expires when the max session lifespan has been reached, then logs you out when the
- // cookie disappears.
- this.keycloak.init({onLoad: "login-required", checkLoginIframe: true, checkLoginIframeInterval: 5, })
- .success((authenticated) => {
- if (authenticated) {
- this.onKeycloakAuthSuccess()
- } else {
- this.onKeycloakAuthFailure()
- }
- })
- .error((e) => {
- this.set("error", e)
- });
+
+ let initOptions = {
+ checkLoginIframe: false, // Disable login status iframe checking, it doesn't work well with offline tokens
+ refreshToken: this.getNativeOfflineRefreshToken() // Try to use a stored offline refresh token
+ }
+
+ if (initOptions.refreshToken) {
+ console.log("Using native shell offline refresh token to initialize Keycloak");
+ }
+
+ // Always force a login when Keycloak clears tokens or isn't happy with the refresh token
+ this.keycloak.onAuthLogout = () => {
+ console.log("On authentication logout (Keycloak tokens cleared?), doing login");
+ this.doKeycloakLogin()
+ }
+ this.keycloak.onAuthRefreshError = () => {
+ console.log("On authentication update token failure (Keycloak invalid refresh token?), doing login");
+ this.doKeycloakLogin()
+ }
+
+ this.keycloak.init(initOptions).success((authenticated) => {
+ if (authenticated) {
+ this.onKeycloakAuthSuccess()
+ } else {
+ console.log("On authentication failure, doing login");
+ this.doKeycloakLogin()
+ }
+ }).error((e) => {
+ this.set("error", e)
+ });
}
onKeycloakAuthSuccess() {
- console.log("Keycloak authentication successful");
-
+ // If native shell is enabled, we need an offline refresh token
if (this.shellNative && this.shellNative.enabled) {
- // Transfer tokens to native shell so they can be stored for future usage
+
+ // If we don't have an offline refresh token, try to get one
+ if (this.keycloak.refreshTokenParsed.typ !== "Offline") {
+ console.debug("Native shell enabled, requesting offline refresh token")
+ this.doKeycloakLogin()
+ return;
+ }
+
+ // Transfer offline refresh token to native shell so it can be stored for future usage
+ console.debug("Native shell enabled, storing offline refresh token");
this.shellNative.postNativeShellMessage({
type: 'token',
- data: {
- token: this.keycloak.token,
- refreshToken: this.keycloak.refreshToken,
- idToken: this.keycloak.idToken
- }
+ data: {refreshToken: this.keycloak.refreshToken}
});
}
- // Set authenticated user
+
+ console.log("Keycloak authentication successful");
this.set("user", this.keycloak.tokenParsed.preferred_username);
this.set("authenticated", true);
- }
- onKeycloakAuthFailure() {
- console.log("Keycloak authentication failure");
+ // Check every 10 seconds if the refresh token can still get an access token
+ if (this.keycloakUpdateTokenInterval) {
+ clearInterval(this.keycloakUpdateTokenInterval);
+ }
+ this.keycloakUpdateTokenInterval = setInterval(() => {
+ this.updateKeycloakAccessToken()
+ }, 10000);
+ }
+ doKeycloakLogin() {
if (this.login) {
- console.debug("Login required, trying again for realm: " + this.realm);
-
+ console.debug("Attempting login for realm: " + this.realm);
let options = {};
if (this.shellNative && this.shellNative.enabled) {
-
- // If we run in native shell, always try to use or obtain an offline refresh token
- console.debug("Native shell enabled, login attempt with scope_offline");
+ // If we run in native shell, request offline token
+ console.debug("Native shell enabled, login attempt with scope=offline_access");
options.scope = "offline_access";
-
- // Get offline token from native shell to try again
- let savedTokensString = this.shellNative.readNativeShellMessage('token');
- if (savedTokensString && savedTokensString.length > 0) {
- console.debug("Native shell has stored offline tokens, using them for next login attempt");
- let savedTokens = JSON.parse(savedTokensString);
- // TODO We should only need the refresh token?
- this.keycloak.token = savedTokens.token;
- this.keycloak.refreshToken = savedTokens.refreshToken;
- this.keycloak.idToken = savedTokens.idToken;
- }
}
this.keycloak.login(options);
}
}
+ updateKeycloakAccessToken(callback) {
+ // Access token must be good for X more seconds, should be half of Constants.ACCESS_TOKEN_LIFESPAN_SECONDS
+ this.keycloak.updateToken(30)
+ .success((tokenRefreshed) => {
+ // If refreshed from server, it means the refresh token was still good for another access token
+ console.debug("Access token update success, refreshed from server: " + tokenRefreshed);
+ callback && callback(tokenRefreshed)
+ })
+ .error(() => {
+ // Refresh token expired (either SSO max session duration or offline idle timeout), see
+ // IDENTITY_SESSION_MAX_MINUTES and IDENTITY_SESSION_OFFLINE_TIMEOUT_MINUTES server config
+ console.info("Access token update failed, refresh token expired, login required");
+ this.doKeycloakLogin();
+ });
+ }
+
+ getNativeOfflineRefreshToken() {
+ if (this.shellNative && this.shellNative.enabled) {
+ let storedToken = this.shellNative.readNativeShellMessage('token');
+ if (storedToken && storedToken.length > 0) {
+ let storedTokenParsed = JSON.parse(storedToken);
+ return storedTokenParsed.refreshToken;
+ }
+ }
+ return undefined;
+ }
+
startBasicAuthentication() {
console.debug("Basic authentication init");
diff --git a/client/src/main/webapp/src/or-app/or-app.html b/client/src/main/webapp/src/or-app/or-app.html
index b6e11f999..e8406b42c 100644
--- a/client/src/main/webapp/src/or-app/or-app.html
+++ b/client/src/main/webapp/src/or-app/or-app.html
@@ -320,24 +320,29 @@
}
onAppError(error) {
- console.error("Application error, disabling app: " + error);
-
- // Remove all slotted children, effectively disabling the app
- this.$.slot.assignedNodes({flatten: false}).forEach((node) => {
- node.parentElement.removeChild(node);
- });
+ console.error("Application error: " + error);
// Disable login/token refresh
this.set("login", false);
this.disconnectEvents();
- // Hide the slots
- this.$.slots.style.display = "none";
+ // If we run in native shell, show native error screen
+ if (this.$.shellNative.enabled) {
+ this.$.shellNative.postNativeShellMessage({type: 'error', data: {error: error}});
+ } else {
+ // Remove all slotted children, effectively disabling the app
+ this.$.slot.assignedNodes({flatten: false}).forEach((node) => {
+ node.parentElement.removeChild(node);
+ });
+
+ // Hide the slots
+ this.$.slots.style.display = "none";
- this.hideBusyIndicator();
+ this.hideBusyIndicator();
- // Fire an event so others can react to an error
- window.dispatchEvent(new CustomEvent("AppError", {detail: {app: this, error: error}}));
+ // Fire an event so others can react to an error
+ window.dispatchEvent(new CustomEvent("AppError", {detail: {app: this, error: error}}));
+ }
}
showApp() {
@@ -427,7 +432,6 @@
// Close socket on unload/refresh of page
window.addEventListener("beforeunload", () => {
- console.log("Page unloaded, closing event service connection");
this.disconnectEvents();
});
@@ -473,7 +477,7 @@
for (let listener of this.webSocketCloseListeners) {
listener();
}
- console.log("Closing WebSocket");
+ console.log("Closing event service connection");
this.webSocket.close();
}
}
diff --git a/client/src/main/webapp/src/or-asset-list/or-asset-list.html b/client/src/main/webapp/src/or-asset-list/or-asset-list.html
index 500fd2e15..44001d3d7 100644
--- a/client/src/main/webapp/src/or-asset-list/or-asset-list.html
+++ b/client/src/main/webapp/src/or-asset-list/or-asset-list.html
@@ -58,11 +58,6 @@
this.set("assetTemplate", assetTemplate);
}
- connectedCallback() {
- super.connectedCallback();
- this.showComponent();
- }
-
executeQuery(selectInclude, assetType) {
// If called without parameters, use last known parameters
diff --git a/client/src/main/webapp/src/or-checkbox/or-checkbox.html b/client/src/main/webapp/src/or-checkbox/or-checkbox.html
index 0a9d2edee..7993402eb 100644
--- a/client/src/main/webapp/src/or-checkbox/or-checkbox.html
+++ b/client/src/main/webapp/src/or-checkbox/or-checkbox.html
@@ -57,12 +57,6 @@
this.dispatchEvent(new CustomEvent("change", {detail: this.checked}));
});
}
-
- connectedCallback() {
- super.connectedCallback();
- this.showComponent();
- }
-
}
defineAppElement(OpenRemoteCheckbox, OpenRemoteCheckbox.is, "Checkbox");
diff --git a/container/src/main/java/org/openremote/container/persistence/PersistenceService.java b/container/src/main/java/org/openremote/container/persistence/PersistenceService.java
index 132fc8bde..bdb61fa69 100644
--- a/container/src/main/java/org/openremote/container/persistence/PersistenceService.java
+++ b/container/src/main/java/org/openremote/container/persistence/PersistenceService.java
@@ -74,7 +74,7 @@ public class PersistenceService implements ContainerService {
public static final String DATABASE_MAX_POOL_SIZE = "DATABASE_MAX_POOL_SIZE";
public static final int DATABASE_MAX_POOL_SIZE_DEFAULT = 20;
public static final String DATABASE_CONNECTION_TIMEOUT_SECONDS = "DATABASE_CONNECTION_TIMEOUT_SECONDS";
- public static final int DATABASE_CONNECTION_TIMEOUT_SECONDS_DEFAULT = 300;
+ public static final int DATABASE_CONNECTION_TIMEOUT_SECONDS_DEFAULT = 5;
protected MessageBrokerService messageBrokerService;
protected Database database;
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 fc95011f2..bd233eae5 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
@@ -79,8 +79,6 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
public static final String KEYCLOAK_CLIENT_POOL_SIZE = "KEYCLOAK_CLIENT_POOL_SIZE";
public static final int KEYCLOAK_CLIENT_POOL_SIZE_DEFAULT = 20;
- public static final String IDENTITY_SESSION_TIMEOUT_MINUTES = "IDENTITY_SESSION_TIMEOUT_MINUTES";
- public static final int IDENTITY_SESSION_TIMEOUT_MINUTES_DEFAULT = 60 * 24; // 1 day
public static final String IDENTITY_SESSION_MAX_MINUTES = "IDENTITY_SESSION_MAX_MINUTES";
public static final int IDENTITY_SESSION_MAX_MINUTES_DEFAULT = 60 * 24; // 1 day
public static final String IDENTITY_SESSION_OFFLINE_TIMEOUT_MINUTES = "IDENTITY_SESSION_OFFLINE_TIMEOUT_MINUTES";
@@ -120,14 +118,14 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
this.clientId = clientId;
this.externalServerUri = externalServerUri;
- sessionTimeoutSeconds = getInteger(container.getConfig(), IDENTITY_SESSION_TIMEOUT_MINUTES, IDENTITY_SESSION_TIMEOUT_MINUTES_DEFAULT) * 60;
- if (sessionTimeoutSeconds < 60) {
- throw new IllegalArgumentException(IDENTITY_SESSION_TIMEOUT_MINUTES + " must be more than 1 minute");
- }
sessionMaxSeconds = getInteger(container.getConfig(), IDENTITY_SESSION_MAX_MINUTES, IDENTITY_SESSION_MAX_MINUTES_DEFAULT) * 60;
if (sessionMaxSeconds < 60) {
throw new IllegalArgumentException(IDENTITY_SESSION_MAX_MINUTES + " must be more than 1 minute");
}
+ // Use the same, as a session is never idle because we periodically check if the refresh token is
+ // still good in frontend code, this check will reset the idle timeout anyway
+ sessionTimeoutSeconds = sessionMaxSeconds;
+
sessionOfflineTimeoutSeconds = getInteger(container.getConfig(), IDENTITY_SESSION_OFFLINE_TIMEOUT_MINUTES, IDENTITY_SESSION_OFFLINE_TIMEOUT_MINUTES_DEFAULT) * 60;
if (sessionOfflineTimeoutSeconds < 60) {
throw new IllegalArgumentException(IDENTITY_SESSION_OFFLINE_TIMEOUT_MINUTES + " must be more than 1 minute");
diff --git a/container/src/main/java/org/openremote/container/util/UniqueIdentifierGenerator.java b/container/src/main/java/org/openremote/container/util/UniqueIdentifierGenerator.java
index e1523f905..2164ba643 100644
--- a/container/src/main/java/org/openremote/container/util/UniqueIdentifierGenerator.java
+++ b/container/src/main/java/org/openremote/container/util/UniqueIdentifierGenerator.java
@@ -66,7 +66,7 @@ public class UniqueIdentifierGenerator implements IdentifierGenerator {
}
/**
- * Generates the same UUID value encoded as Base62, 22 characters long, if the bytes are given.
+ * Generates the same UUID value encoded as Base62, 22 characters long, if the bytes are the same.
*/
public static String generateId(byte[] bytes) {
return Url62.encode(nameGenerator.generate(bytes));
diff --git a/manager/src/main/resources/demo/rules/DemoResidenceAutoVentilation.groovy b/manager/src/main/resources/demo/rules/DemoResidenceAutoVentilation.groovy
index ea0c92a9d..6a8648bf4 100644
--- a/manager/src/main/resources/demo/rules/DemoResidenceAutoVentilation.groovy
+++ b/manager/src/main/resources/demo/rules/DemoResidenceAutoVentilation.groovy
@@ -52,9 +52,9 @@ Closure<Boolean> roomThresholdMatch =
// Any room of the residence which has a level greater than zero
def roomWithMaxLevel = facts.matchAssetState(
new AssetQuery().type(ROOM).parent(residence.id).attributeValue(attribute, GREATER_THAN, 0)
- ).max { roomWithLevelAboveZero ->
+ ).max { roomA, roomB ->
// get the room with the highest level
- roomWithLevelAboveZero.valueAsNumber.orElse(0)
+ Double.compare(roomA.valueAsNumber.orElse(0), roomB.valueAsNumber.orElse(0))
}
if (roomWithMaxLevel.isPresent()) {
diff --git a/profile/deploy.yml b/profile/deploy.yml
index dd406df30..cd062a4b6 100644
--- a/profile/deploy.yml
+++ b/profile/deploy.yml
@@ -207,12 +207,10 @@ services:
# For the Keycloak identity provider, you may configure session timeouts of frontend apps. This
# will only be applied on newly created realms, or once on the master realm when clean setup runs.
#
- # The idle session timeout, logging the user out if no requests are made, default is 1 day.
- # Note that WebSocket events do not count as requests and therefore do not extend the session!
- # IDENTITY_SESSION_TIMEOUT_MINUTES : 1440
- # The max session lifespan, always logging the user out when expired, default is 1 day.
+ # Validity of non-offline refresh tokens, force login when expired on web app, default is 1 day.
# IDENTITY_SESSION_MAX_MINUTES: 1440
- # The max offline token lifespan, forcing login on native console when app not used, default is 14 days.
+ #
+ # Validity of offline refresh tokens, force login on native console app, default is 14 days.
# IDENTITY_SESSION_OFFLINE_TIMEOUT_MINUTES: 20160
# Location of the static manager (UI and API) resources, you don't need to override this