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
Work on basic identity service and rpi3 platform, demo deployment complete
Christian Bauerbf6492b0223e
diff --git a/container/build.gradle b/container/build.gradleindex 70571f1cc..d01d4cf50 100644--- a/container/build.gradle+++ b/container/build.gradle@@ -47,7 +47,9 @@ dependencies {compile "org.apache.camel:camel-script:$camelVersion"compile "org.apache.camel:camel-groovy:$camelVersion"- compile "com.fasterxml.uuid:java-uuid-generator:$uuidGeneratorVersion"+ compile ("com.fasterxml.uuid:java-uuid-generator:$uuidGeneratorVersion") {+ exclude group: "log4j"+ }// Test environment dependenciescompile "org.glassfish.tyrus:tyrus-client:$tyrusVersion"diff --git a/container/src/main/java/org/openremote/container/persistence/Database.java b/container/src/main/java/org/openremote/container/persistence/Database.javaindex 9326b31d3..4301bceac 100644--- a/container/src/main/java/org/openremote/container/persistence/Database.java+++ b/container/src/main/java/org/openremote/container/persistence/Database.java@@ -64,6 +64,7 @@ public interface Database {hikariConfig.setUsername(username);hikariConfig.setPassword(password);hikariConfig.setConnectionTimeout(connectionTimeoutSeconds * 1000);+ hikariConfig.setInitializationFailTimeout(connectionTimeoutSeconds * 1000);hikariConfig.setMinimumIdle(minIdle);hikariConfig.setMaximumPoolSize(maxPoolSize);diff --git a/container/src/main/java/org/openremote/container/persistence/PersistenceService.java b/container/src/main/java/org/openremote/container/persistence/PersistenceService.javaindex 40a2fd5e1..4b70ddf16 100644--- a/container/src/main/java/org/openremote/container/persistence/PersistenceService.java+++ b/container/src/main/java/org/openremote/container/persistence/PersistenceService.java@@ -36,7 +36,8 @@ import java.util.function.Function;import java.util.logging.Level;import java.util.logging.Logger;-import static org.openremote.container.util.MapAccess.*;+import static org.openremote.container.util.MapAccess.getInteger;+import static org.openremote.container.util.MapAccess.getString;public class PersistenceService implements ContainerService {diff --git a/container/src/main/java/org/openremote/container/security/IdentityService.java b/container/src/main/java/org/openremote/container/security/IdentityService.javaindex ed3606168..06c70e7cd 100644--- a/container/src/main/java/org/openremote/container/security/IdentityService.java+++ b/container/src/main/java/org/openremote/container/security/IdentityService.java@@ -22,6 +22,7 @@ package org.openremote.container.security;import io.undertow.servlet.api.DeploymentInfo;import org.openremote.container.Container;import org.openremote.container.ContainerService;+import org.openremote.container.security.keycloak.KeycloakIdentityProvider;import javax.ws.rs.core.UriBuilder;import java.util.logging.Logger;@@ -76,9 +77,18 @@ public abstract class IdentityService implements ContainerService {public void secureDeployment(DeploymentInfo deploymentInfo) {LOG.info("Securing web deployment: " + deploymentInfo.getContextPath());+ deploymentInfo.addOuterHandlerChainWrapper(AuthOverloadHandler::new);+ deploymentInfo.setSecurityDisabled(false);getIdentityProvider().secureDeployment(deploymentInfo);}+ /**+ * If Keycloak is enabled, support multi-tenancy.+ */+ public boolean isKeycloakEnabled() {+ return getIdentityProvider() instanceof KeycloakIdentityProvider;+ }+/*** To initialize the {@link IdentityProvider}, subclasses should override {@link #init(Container)}.*/diff --git a/container/src/main/java/org/openremote/container/security/basic/BasicAuthContext.java b/container/src/main/java/org/openremote/container/security/basic/BasicAuthContext.javanew file mode 100644index 000000000..66a2cd0b6--- /dev/null+++ b/container/src/main/java/org/openremote/container/security/basic/BasicAuthContext.java@@ -0,0 +1,71 @@+/*+ * 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.basic;++import org.openremote.container.security.AuthContext;++import java.security.Principal;++/**+ * Basic authorization, any user has all roles and is superuser.+ */+public class BasicAuthContext implements AuthContext, Principal {++ private final String authenticatedRealm;+ private final String userId;+ private final String username;++ public BasicAuthContext(String authenticatedRealm, String userId, String username) {+ this.authenticatedRealm = authenticatedRealm;+ this.userId = userId;+ this.username = username;+ }++ @Override+ public String getName() {+ return username;+ }+++ @Override+ public String getAuthenticatedRealm() {+ return authenticatedRealm;+ }++ @Override+ public String getUsername() {+ return username;+ }++ @Override+ public String getUserId() {+ return userId;+ }++ @Override+ public boolean hasRealmRole(String role) {+ return true;+ }++ @Override+ public boolean hasResourceRole(String role, String resource) {+ return true;+ }+}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.javaindex 01c2569ce..6e1b26359 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,11 +19,19 @@*/package org.openremote.container.security.basic;+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.servlet.api.DeploymentInfo;+import io.undertow.servlet.api.LoginConfig;import org.openremote.container.security.IdentityProvider;-// TODO-public class BasicIdentityProvider implements IdentityProvider{+import java.util.logging.Logger;++public abstract class BasicIdentityProvider implements IdentityProvider {++ private static final Logger LOG = Logger.getLogger(BasicIdentityProvider.class.getName());@Overridepublic void start() {@@ -37,6 +45,31 @@ public class BasicIdentityProvider implements IdentityProvider{@Overridepublic void secureDeployment(DeploymentInfo deploymentInfo) {+ LoginConfig loginConfig = new LoginConfig("BASIC", "OpenRemote");+ 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;+ }+ });}++ abstract protected Account verifyAccount(String username, char[] password);}diff --git a/container/src/main/java/org/openremote/container/security/basic/PasswordStorage.java b/container/src/main/java/org/openremote/container/security/basic/PasswordStorage.javanew file mode 100644index 000000000..25398e775--- /dev/null+++ b/container/src/main/java/org/openremote/container/security/basic/PasswordStorage.java@@ -0,0 +1,289 @@+/**+ * Copyright (c) 2016, Taylor Hornby+ * All rights reserved.+ * <p>+ * Redistribution and use in source and binary forms, with or without modification,+ * are permitted provided that the following conditions are met:+ * <p>+ * 1. Redistributions of source code must retain the above copyright notice, this+ * list of conditions and the following disclaimer.+ * <p>+ * 2. Redistributions in binary form must reproduce the above copyright notice,+ * this list of conditions and the following disclaimer in the documentation and/or+ * other materials provided with the distribution.+ * <p>+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.+ */+package org.openremote.container.security.basic;++import com.google.common.cache.CacheBuilder;+import com.google.common.cache.CacheLoader;+import com.google.common.cache.LoadingCache;++import javax.crypto.SecretKeyFactory;+import javax.crypto.spec.PBEKeySpec;+import javax.xml.bind.DatatypeConverter;+import java.security.NoSuchAlgorithmException;+import java.security.SecureRandom;+import java.security.spec.InvalidKeySpecException;+import java.util.Arrays;+import java.util.concurrent.ExecutionException;+import java.util.logging.Logger;++import static java.util.concurrent.TimeUnit.DAYS;++/**+ * https://github.com/defuse/password-hashing+ * <p>+ * TODO: On ARM32 this is very slow, even with only 500 iterations it takes ~2 seconds on an RPI3 to hash a password, so we cache the result+ * TODO: Remove the cache if ARM64 is fast enough and increase iterations+ */+public class PasswordStorage {++ private static final Logger LOG = Logger.getLogger(PasswordStorage.class.getName());++ static class CacheKey {+ final public char[] password;+ final public byte[] salt;+ final public int iterations;+ final public int bytes;++ public CacheKey(char[] password, byte[] salt, int iterations, int bytes) {+ this.password = password;+ this.salt = salt;+ this.iterations = iterations;+ this.bytes = bytes;+ }++ @Override+ public boolean equals(Object o) {+ if (this == o) return true;+ if (o == null || getClass() != o.getClass()) return false;++ CacheKey cacheKey = (CacheKey) o;++ if (iterations != cacheKey.iterations) return false;+ if (bytes != cacheKey.bytes) return false;+ if (!Arrays.equals(password, cacheKey.password)) return false;+ return Arrays.equals(salt, cacheKey.salt);+ }++ @Override+ public int hashCode() {+ int result = Arrays.hashCode(password);+ result = 31 * result + Arrays.hashCode(salt);+ result = 31 * result + iterations;+ result = 31 * result + bytes;+ return result;+ }+ }++ static final protected LoadingCache<CacheKey, byte[]> hashedPasswordCache = CacheBuilder.newBuilder()+ .maximumSize(1000)+ .expireAfterWrite(7, DAYS)+ .build(new CacheLoader<CacheKey, byte[]>() {+ @Override+ public byte[] load(CacheKey key) throws Exception {+ try {+ LOG.fine("Cache miss, hashing password...") ;+ PBEKeySpec spec = new PBEKeySpec(key.password, key.salt, key.iterations, key.bytes * 8);+ SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);+ return skf.generateSecret(spec).getEncoded();+ } catch (NoSuchAlgorithmException ex) {+ throw new CannotPerformOperationException(+ "Hash algorithm not supported.",+ ex+ );+ } catch (InvalidKeySpecException ex) {+ throw new CannotPerformOperationException(+ "Invalid key spec.",+ ex+ );+ }+ }+ });++ @SuppressWarnings("serial")+ static public class InvalidHashException extends RuntimeException {+ public InvalidHashException(String message) {+ super(message);+ }++ public InvalidHashException(String message, Throwable source) {+ super(message, source);+ }+ }++ @SuppressWarnings("serial")+ static public class CannotPerformOperationException extends RuntimeException {+ public CannotPerformOperationException(String message) {+ super(message);+ }++ public CannotPerformOperationException(String message, Throwable source) {+ super(message, source);+ }+ }++ public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1";++ // These constants may be changed without breaking existing hashes.+ public static final int SALT_BYTE_SIZE = 24;+ public static final int HASH_BYTE_SIZE = 18;+ public static final int PBKDF2_ITERATIONS = 500; // TODO Try to increase this to >1000 on ARM64 if fast enough++ // These constants define the encoding and may not be changed.+ public static final int HASH_SECTIONS = 5;+ public static final int HASH_ALGORITHM_INDEX = 0;+ public static final int ITERATION_INDEX = 1;+ public static final int HASH_SIZE_INDEX = 2;+ public static final int SALT_INDEX = 3;+ public static final int PBKDF2_INDEX = 4;++ public static String createHash(String password)+ throws CannotPerformOperationException {+ return createHash(password.toCharArray());+ }++ public static String createHash(char[] password)+ throws CannotPerformOperationException {+ // Generate a random salt+ SecureRandom random = new SecureRandom();+ byte[] salt = new byte[SALT_BYTE_SIZE];+ random.nextBytes(salt);++ // Hash the password+ byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);+ int hashSize = hash.length;++ // format: algorithm:iterations:hashSize:salt:hash+ String parts = "sha1:" ++ PBKDF2_ITERATIONS ++ ":" + hashSize ++ ":" ++ toBase64(salt) ++ ":" ++ toBase64(hash);+ return parts;+ }++ public static boolean verifyPassword(String password, String correctHash)+ throws CannotPerformOperationException, InvalidHashException {+ return verifyPassword(password.toCharArray(), correctHash);+ }++ public static boolean verifyPassword(char[] password, String correctHash)+ throws CannotPerformOperationException, InvalidHashException {+ // Decode the hash into its parameters+ String[] params = correctHash.split(":");+ if (params.length != HASH_SECTIONS) {+ throw new InvalidHashException(+ "Fields are missing from the password hash."+ );+ }++ // Currently, Java only supports SHA1.+ if (!params[HASH_ALGORITHM_INDEX].equals("sha1")) {+ throw new CannotPerformOperationException(+ "Unsupported hash type."+ );+ }++ int iterations = 0;+ try {+ iterations = Integer.parseInt(params[ITERATION_INDEX]);+ } catch (NumberFormatException ex) {+ throw new InvalidHashException(+ "Could not parse the iteration count as an integer.",+ ex+ );+ }++ if (iterations < 1) {+ throw new InvalidHashException(+ "Invalid number of iterations. Must be >= 1."+ );+ }+++ byte[] salt = null;+ try {+ salt = fromBase64(params[SALT_INDEX]);+ } catch (IllegalArgumentException ex) {+ throw new InvalidHashException(+ "Base64 decoding of salt failed.",+ ex+ );+ }++ byte[] hash = null;+ try {+ hash = fromBase64(params[PBKDF2_INDEX]);+ } catch (IllegalArgumentException ex) {+ throw new InvalidHashException(+ "Base64 decoding of pbkdf2 output failed.",+ ex+ );+ }+++ int storedHashSize = 0;+ try {+ storedHashSize = Integer.parseInt(params[HASH_SIZE_INDEX]);+ } catch (NumberFormatException ex) {+ throw new InvalidHashException(+ "Could not parse the hash size as an integer.",+ ex+ );+ }++ if (storedHashSize != hash.length) {+ throw new InvalidHashException(+ "Hash length doesn't match stored hash length."+ );+ }++ // Compute the hash of the provided password, using the same salt,+ // iteration count, and hash length+ byte[] testHash = pbkdf2(password, salt, iterations, hash.length);+ // Compare the hashes in constant time. The password is correct if+ // both hashes match.+ return slowEquals(hash, testHash);+ }++ private static boolean slowEquals(byte[] a, byte[] b) {+ int diff = a.length ^ b.length;+ for (int i = 0; i < a.length && i < b.length; i++)+ diff |= a[i] ^ b[i];+ return diff == 0;+ }++ private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes) {+ try {+ return hashedPasswordCache.get(+ new CacheKey(password, salt, iterations, bytes)+ );+ } catch (ExecutionException ex) {+ throw new RuntimeException(ex.getCause());+ }+ }++ private static byte[] fromBase64(String hex)+ throws IllegalArgumentException {+ return DatatypeConverter.parseBase64Binary(hex);+ }++ private static String toBase64(byte[] array) {+ return DatatypeConverter.printBase64Binary(array);+ }++}\ No newline at end of filediff --git a/container/src/main/java/org/openremote/container/security/keycloak/KeycloakIdentityProvider.java b/container/src/main/java/org/openremote/container/security/keycloak/KeycloakIdentityProvider.javaindex fb6a33a92..6171b1b3b 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@@ -182,8 +182,6 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider{@Overridepublic void secureDeployment(DeploymentInfo deploymentInfo) {- deploymentInfo.addOuterHandlerChainWrapper(AuthOverloadHandler::new);- deploymentInfo.setSecurityDisabled(false);LoginConfig loginConfig = new LoginConfig(SimpleKeycloakServletExtension.AUTH_MECHANISM, "OpenRemote");deploymentInfo.setLoginConfig(loginConfig);deploymentInfo.addServletExtension(new SimpleKeycloakServletExtension(keycloakConfigResolver));diff --git a/container/src/main/java/org/openremote/container/web/DefaultWebsocketComponent.java b/container/src/main/java/org/openremote/container/web/DefaultWebsocketComponent.javaindex 83e6fe62f..80ccc6e83 100644--- a/container/src/main/java/org/openremote/container/web/DefaultWebsocketComponent.java+++ b/container/src/main/java/org/openremote/container/web/DefaultWebsocketComponent.java@@ -27,8 +27,9 @@ import io.undertow.websockets.jsr.DefaultContainerConfigurator;import io.undertow.websockets.jsr.UndertowContainerProvider;import io.undertow.websockets.jsr.WebSocketDeploymentInfo;import org.keycloak.KeycloakPrincipal;-import org.keycloak.KeycloakSecurityContext;import org.openremote.container.message.MessageBrokerSetupService;+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.IdentityService;import org.openremote.container.web.socket.WebsocketAdapter;@@ -45,9 +46,11 @@ import javax.websocket.HandshakeResponse;import javax.websocket.server.HandshakeRequest;import javax.websocket.server.ServerEndpointConfig;import javax.ws.rs.WebApplicationException;+import java.security.Principal;import java.util.logging.Logger;import static javax.ws.rs.core.Response.Status.FORBIDDEN;+import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;public class DefaultWebsocketComponent extends WebsocketComponent {@@ -89,21 +92,26 @@ public class DefaultWebsocketComponent extends WebsocketComponent {@Overridepublic void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {- KeycloakPrincipal<KeycloakSecurityContext> keycloakPrincipal =- (KeycloakPrincipal<KeycloakSecurityContext>) request.getUserPrincipal();- if (keycloakPrincipal == null) {- throw new WebApplicationException(- "Websocket session is not authenticated, can't access user principal", FORBIDDEN- );+ Principal principal = request.getUserPrincipal();+ if (principal == null) {+ throw new WebApplicationException("Request is not authenticated, can't access user principal", FORBIDDEN);}- config.getUserProperties().put(- WebsocketConstants.HANDSHAKE_AUTH,- new AccessTokenAuthContext(+ AuthContext authContext;++ if (principal instanceof KeycloakPrincipal) {+ KeycloakPrincipal keycloakPrincipal = (KeycloakPrincipal) principal;+ authContext = new AccessTokenAuthContext(keycloakPrincipal.getKeycloakSecurityContext().getRealm(),keycloakPrincipal.getKeycloakSecurityContext().getToken()- )- );+ );+ } else if (principal instanceof BasicAuthContext) {+ authContext = (BasicAuthContext) principal;+ } else {+ throw new WebApplicationException("Unsupported user principal type: " + principal, INTERNAL_SERVER_ERROR);+ }++ config.getUserProperties().put(WebsocketConstants.HANDSHAKE_AUTH, authContext);super.modifyHandshake(config, request, response);}diff --git a/container/src/main/java/org/openremote/container/web/WebResource.java b/container/src/main/java/org/openremote/container/web/WebResource.javaindex 34ec68ca9..e32244fd1 100644--- a/container/src/main/java/org/openremote/container/web/WebResource.java+++ b/container/src/main/java/org/openremote/container/web/WebResource.java@@ -20,8 +20,8 @@package org.openremote.container.web;import org.keycloak.KeycloakPrincipal;-import org.keycloak.KeycloakSecurityContext;import org.openremote.container.Container;+import org.openremote.container.security.basic.BasicAuthContext;import org.openremote.container.security.keycloak.AccessTokenAuthContext;import org.openremote.container.security.AuthContext;@@ -29,7 +29,10 @@ import javax.servlet.http.HttpServletRequest;import javax.ws.rs.WebApplicationException;import javax.ws.rs.core.*;+import java.security.Principal;+import static javax.ws.rs.core.Response.Status.FORBIDDEN;+import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;public class WebResource implements AuthContext {@@ -63,15 +66,22 @@ public class WebResource implements AuthContext {@SuppressWarnings("unchecked")public AuthContext getAuthContext() {// The securityContext is a thread-local proxy, careful when/how you call it- KeycloakPrincipal<KeycloakSecurityContext> principal =- (KeycloakPrincipal<KeycloakSecurityContext>) securityContext.getUserPrincipal();+ Principal principal = securityContext.getUserPrincipal();if (principal == null) {throw new WebApplicationException("Request is not authenticated, can't access user principal", FORBIDDEN);}- return new AccessTokenAuthContext(- principal.getKeycloakSecurityContext().getRealm(),- principal.getKeycloakSecurityContext().getToken()- );++ 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);+ }}// Convenience methodsdiff --git a/container/src/main/java/org/openremote/container/web/WebService.java b/container/src/main/java/org/openremote/container/web/WebService.javaindex 53a8cdc46..f8fb6f33a 100644--- a/container/src/main/java/org/openremote/container/web/WebService.java+++ b/container/src/main/java/org/openremote/container/web/WebService.java@@ -249,7 +249,7 @@ public abstract class WebService implements ContainerService {throw new RuntimeException("No identity service deployed, can't enable API security");}- return addServletDeployment(identityService, deploymentInfo, true);+ return addServletDeployment(identityService, deploymentInfo, resteasyDeployment.isSecurityEnabled());}protected HttpHandler createJsApiHandler(IdentityService identityService, ResteasyDeployment resteasyDeployment) {@@ -279,9 +279,9 @@ public abstract class WebService implements ContainerService {/*** Adds a deployment to the default servlet container and returns the started handler.*- * @param identityService Must not be null if secure deployment is used, source of configuration for the Keycloak extension+ * @param identityService Must not be null if secure deployment is used* @param deploymentInfo The deployment to add to the default container- * @param secure If Keycloak extension should be enabled for this deployment+ * @param secure If authentication/authorization should be enabled for this deployment*/public HttpHandler addServletDeployment(IdentityService identityService, DeploymentInfo deploymentInfo, boolean secure) {try {diff --git a/container/src/main/java/org/openremote/container/web/jsapi/JSAPIWriter.java b/container/src/main/java/org/openremote/container/web/jsapi/JSAPIWriter.javaindex 01fc57724..9af806a01 100644--- a/container/src/main/java/org/openremote/container/web/jsapi/JSAPIWriter.java+++ b/container/src/main/java/org/openremote/container/web/jsapi/JSAPIWriter.java@@ -201,8 +201,7 @@ public class JSAPIWriter {printOtherParams(methodMetaData, writer);writer.println(" request.setURI(uri);");writer.println(" if(params.$username && params.$password)");- writer- .println(" request.setCredentials(params.$username, params.$password);");+ writer.println(" request.setCredentials(params.$username, params.$password);");writer.println(" if(params.$accepts)");writer.println(" request.setAccepts(params.$accepts);");if (methodMetaData.getWants() != null) {diff --git a/container/src/main/resources/org/openremote/container/web/jsapi/client.js b/container/src/main/resources/org/openremote/container/web/jsapi/client.jsindex 35a798027..7f1600d7e 100644--- a/container/src/main/resources/org/openremote/container/web/jsapi/client.js+++ b/container/src/main/resources/org/openremote/container/web/jsapi/client.js@@ -61,7 +61,16 @@ REST.Request.prototype = {document.cookie = encodeURI(this.cookies[i][0])+ "=" + encodeURI(this.cookies[i][1]);}- request.open(this.method, url, this.async, this.username, this.password);+ if (this.username && this.password) {+ // TODO Must be async false or Safari will popup 401 dialog+ // TODO Must set dummy URL username or Chrome will popup 401 dialog but that leads to weird behavior in Safari...+ request.open(this.method, url, this.async);+ var credentials = "Basic " + btoa(this.username + ":" + this.password);+ request.setRequestHeader("Authorization", credentials);+ } else {+ request.open(this.method, url, this.async);+ }+var acceptSet = false;var contentTypeSet = false;for (var i = 0; i < this.headers.length; i++) {diff --git a/gradle.properties b/gradle.propertiesindex bd4f1aecf..afef075d2 100644--- a/gradle.properties+++ b/gradle.properties@@ -16,11 +16,11 @@ ginVersion = 2.1.2gwtJacksonVersion = 0.14.2jacksonVersion = 2.8.6groovyVersion = 2.4.1-sqliteVersion = 3.8.11.2+sqliteVersion = 3.19.3hibernateVersion = 5.2.2.FinalhibernateValidatorVersion = 5.2.3.FinalpostgresJdbcVersion = 9.4.1209-hikaricpVersion = 2.4.3+hikaricpVersion = 2.6.3junitVersion = 4.12spockVersion = 1.1-groovy-2.4objenesisVersion = 2.2diff --git a/manager/build.gradle b/manager/build.gradleindex 871d0486e..913fea0ce 100644--- a/manager/build.gradle+++ b/manager/build.gradle@@ -4,7 +4,7 @@ task prepareImage(type: Copy) {dependsOn resolveTask(":manager:server:installDist"), resolveTask(":manager:client:installDist")from "${project.projectDir}"into "${project.buildDir}/install"- include("Dockerfile*")+ include("*Dockerfile")}task clean() {diff --git a/manager/client/src/main/java/org/openremote/manager/client/ManagerEntryPoint.java b/manager/client/src/main/java/org/openremote/manager/client/ManagerEntryPoint.javaindex 7027cb673..3735e1b8d 100644--- a/manager/client/src/main/java/org/openremote/manager/client/ManagerEntryPoint.java+++ b/manager/client/src/main/java/org/openremote/manager/client/ManagerEntryPoint.java@@ -21,17 +21,12 @@ package org.openremote.manager.client;import com.google.gwt.core.client.GWT;-import java.util.logging.Logger;-public class ManagerEntryPoint implements com.google.gwt.core.client.EntryPoint {protected final ManagerGinjector injector = GWT.create(ManagerGinjector.class);- private static final Logger LOG = Logger.getLogger(ManagerEntryPoint.class.getName());-@Overridepublic void onModuleLoad() {-injector.getAppController().start();dispatchReadyEvent();}diff --git a/manager/client/src/main/java/org/openremote/manager/client/ManagerModule.java b/manager/client/src/main/java/org/openremote/manager/client/ManagerModule.javaindex 122a4ae1e..7b5dc7af3 100644--- a/manager/client/src/main/java/org/openremote/manager/client/ManagerModule.java+++ b/manager/client/src/main/java/org/openremote/manager/client/ManagerModule.java@@ -110,13 +110,23 @@ public class ManagerModule extends AbstractGinModule {@Provides@Singletonpublic SecurityService getSecurityService(CookieService cookieService, EventBus eventBus) {- return new SecurityServiceImpl(getKeyCloak(), cookieService, eventBus);+ return getKeyCloak() != null+ ? new KeycloakSecurityService(getKeyCloak(), cookieService, eventBus)+ : new BasicSecurityService(getBasicAuthUsername(), getBasicAuthPassword());}public static native Keycloak getKeyCloak() /*-{return $wnd.keycloak;}-*/;+ public static native String getBasicAuthUsername() /*-{+ return $wnd.basicAuthUsername;+ }-*/;++ public static native String getBasicAuthPassword() /*-{+ return $wnd.basicAuthPassword;+ }-*/;+@Provides@Singletonpublic RequestService getRequestService(SecurityService securityService,diff --git a/manager/client/src/main/java/org/openremote/manager/client/app/HeaderPresenter.java b/manager/client/src/main/java/org/openremote/manager/client/app/HeaderPresenter.javaindex 55428bde8..6f2e87116 100644--- a/manager/client/src/main/java/org/openremote/manager/client/app/HeaderPresenter.java+++ b/manager/client/src/main/java/org/openremote/manager/client/app/HeaderPresenter.java@@ -72,7 +72,7 @@ public class HeaderPresenter implements HeaderView.Presenter {event -> assetBrowserSelection = event);- view.setUsername(securityService.getParsedToken().getPreferredUsername());+ view.setUsername(securityService.getUsername());eventBus.register(UserChangeEvent.class,event -> view.setUsername(event.getUsername())diff --git a/manager/client/src/main/java/org/openremote/manager/client/mvp/AppPlaceController.java b/manager/client/src/main/java/org/openremote/manager/client/mvp/AppPlaceController.javaindex 13e9fb633..22f5c54e6 100644--- a/manager/client/src/main/java/org/openremote/manager/client/mvp/AppPlaceController.java+++ b/manager/client/src/main/java/org/openremote/manager/client/mvp/AppPlaceController.java@@ -26,9 +26,8 @@ import com.google.gwt.place.shared.PlaceController;import com.google.web.bindery.event.shared.UmbrellaException;import org.openremote.manager.client.event.GoToPlaceEvent;import org.openremote.manager.client.event.WillGoToPlaceEvent;-import org.openremote.model.event.bus.EventBus;import org.openremote.manager.client.service.SecurityService;-import org.openremote.model.Constants;+import org.openremote.model.event.bus.EventBus;import java.util.logging.Level;import java.util.logging.Logger;@@ -85,19 +84,11 @@ public class AppPlaceController extends PlaceController {@Overridepublic void goTo(Place newPlace) {- securityService.updateToken(- Constants.ACCESS_TOKEN_LIFESPAN_SECONDS/2,- refreshed -> {- // If it wasn't refreshed, it was still valid, in both cases we can continue- // YOU HAVE MADE A GWT ERROR. THIS HELPS YOU FIND IT.- try {- super.goTo(newPlace);- } catch (UmbrellaException ex) {- LOG.log(Level.SEVERE, "Error handling place change to: " + newPlace, ex);- }- },- securityService::logout- );+ try {+ super.goTo(newPlace);+ } catch (UmbrellaException ex) {+ LOG.log(Level.SEVERE, "Error handling place change to: " + newPlace, ex);+ }}public SecurityService getSecurityService() {diff --git a/manager/client/src/main/java/org/openremote/manager/client/service/BasicSecurityService.java b/manager/client/src/main/java/org/openremote/manager/client/service/BasicSecurityService.javanew file mode 100644index 000000000..6d1592654--- /dev/null+++ b/manager/client/src/main/java/org/openremote/manager/client/service/BasicSecurityService.java@@ -0,0 +1,100 @@+/*+ * 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.manager.client.service;++import com.google.gwt.user.client.Window;+import elemental.client.Browser;+import org.openremote.manager.shared.http.RequestParams;+import org.openremote.model.Constants;++import java.util.logging.Logger;++/**+ * Basic authorization, any user has all roles and is superuser.+ */+public class BasicSecurityService implements SecurityService {++ private static final Logger LOG = Logger.getLogger(BasicSecurityService.class.getName());++ protected final String username;+ protected final String password;++ public BasicSecurityService(String username, String password) {+ this.username = username;+ this.password = password;+ }++ @Override+ public String getUsername() {+ return username;+ }++ @Override+ public String getFullName() {+ return username;+ }++ @Override+ public void logout() {+ LOG.fine("Logging out...");+ String url = Window.Location.getProtocol() + "//" + Window.Location.getHost() + "/" + Constants.MASTER_REALM;+ Window.Location.assign(url);+ }++ @Override+ public boolean isSuperUser() {+ return true;+ }++ @Override+ public boolean hasRealmRole(String role) {+ return true;+ }++ @Override+ public boolean hasResourceRole(String role, String resource) {+ return true;+ }++ @Override+ public boolean hasResourceRoleOrIsSuperUser(String role, String resource) {+ return true;+ }++ @Override+ public String getAuthenticatedRealm() {+ return Constants.MASTER_REALM;+ }++ @Override+ public <OUT> void setCredentials(RequestParams<OUT> requestParams) {+ requestParams.setUsername(username);+ requestParams.setPassword(password);+ }++ @Override+ public String setCredentials(String serviceUrl) {+ String authenticatedServiceUrl = serviceUrl+ + "?Auth-Realm=" + getAuthenticatedRealm()+ + "&Authorization=Basic " + Browser.getWindow().btoa(username + ":" + password);+ return authenticatedServiceUrl;+ }++}diff --git a/manager/client/src/main/java/org/openremote/manager/client/service/EventServiceImpl.java b/manager/client/src/main/java/org/openremote/manager/client/service/EventServiceImpl.javaindex a0fd859ec..2b00c21cf 100644--- a/manager/client/src/main/java/org/openremote/manager/client/service/EventServiceImpl.java+++ b/manager/client/src/main/java/org/openremote/manager/client/service/EventServiceImpl.java@@ -164,50 +164,36 @@ public class EventServiceImpl implements EventService {webSocket = null;}- securityService.updateToken(- Constants.ACCESS_TOKEN_LIFESPAN_SECONDS / 2,- refreshed -> {- // If it wasn't refreshed, it was still valid, in both cases we can continue- LOG.fine("Connecting to event websocket: " + serviceUrl);- String authenticatedServiceUrl = serviceUrl- + "?Auth-Realm=" + securityService.getAuthenticatedRealm()- + "&Authorization=Bearer " + securityService.getToken();+ LOG.fine("Connecting to event websocket: " + serviceUrl);- webSocket = Browser.getWindow().newWebSocket(authenticatedServiceUrl);- webSocket.setOnopen(evt -> {- if (webSocket.getReadyState() == WebSocket.OPEN) {- LOG.fine("WebSocket open: " + webSocket.getUrl());- eventBus.dispatch(new SessionOpenedEvent());- }- });- webSocket.setOnclose(evt -> {- CloseEvent closeEvent = (CloseEvent) evt;- if (closeEvent.isWasClean() && closeEvent.getCode() == 1000) {- LOG.fine("WebSocket closed: " + webSocket.getUrl());- eventBus.dispatch(new SessionClosedCleanEvent());- } else {- LOG.fine("WebSocket '" + webSocket.getUrl() + "' closed with error: " + closeEvent.getCode());- eventBus.dispatch(new SessionClosedErrorEvent(- new SessionClosedErrorEvent.Error(closeEvent.getCode(), closeEvent.getReason())- ));- }- });- webSocket.setOnmessage(evt -> {- elemental.events.MessageEvent messageEvent = (elemental.events.MessageEvent) evt;- String data = messageEvent.getData().toString();- LOG.fine("Received data on WebSocket: " + data);- onDataReceived(data);- });- },- () -> {- LOG.fine("Failed to update access token for WebSocket");+ String authenticatedServiceUrl = securityService.setCredentials(serviceUrl);++ webSocket = Browser.getWindow().newWebSocket(authenticatedServiceUrl);+ webSocket.setOnopen(evt -> {+ if (webSocket.getReadyState() == WebSocket.OPEN) {+ LOG.fine("WebSocket open: " + webSocket.getUrl());+ eventBus.dispatch(new SessionOpenedEvent());+ }+ });+ webSocket.setOnclose(evt -> {+ CloseEvent closeEvent = (CloseEvent) evt;+ if (closeEvent.isWasClean() && closeEvent.getCode() == 1000) {+ LOG.fine("WebSocket closed: " + webSocket.getUrl());+ eventBus.dispatch(new SessionClosedCleanEvent());+ } else {+ LOG.fine("WebSocket '" + webSocket.getUrl() + "' closed with error: " + closeEvent.getCode());eventBus.dispatch(new SessionClosedErrorEvent(- new SessionClosedErrorEvent.Error(4000, "Failed to update access token")+ new SessionClosedErrorEvent.Error(closeEvent.getCode(), closeEvent.getReason())));}- );-+ });+ webSocket.setOnmessage(evt -> {+ elemental.events.MessageEvent messageEvent = (elemental.events.MessageEvent) evt;+ String data = messageEvent.getData().toString();+ LOG.fine("Received data on WebSocket: " + data);+ onDataReceived(data);+ });}@Overridediff --git a/manager/client/src/main/java/org/openremote/manager/client/service/SecurityServiceImpl.java b/manager/client/src/main/java/org/openremote/manager/client/service/KeycloakSecurityService.javasimilarity index 56%rename from manager/client/src/main/java/org/openremote/manager/client/service/SecurityServiceImpl.javarename to manager/client/src/main/java/org/openremote/manager/client/service/KeycloakSecurityService.javaindex 95c474fd5..91bc6fbb5 100644--- a/manager/client/src/main/java/org/openremote/manager/client/service/SecurityServiceImpl.java+++ b/manager/client/src/main/java/org/openremote/manager/client/service/KeycloakSecurityService.java@@ -19,27 +19,29 @@*/package org.openremote.manager.client.service;-import com.google.inject.Inject;import elemental.client.Browser;import elemental.html.Location;import org.openremote.manager.client.event.UserChangeEvent;-import org.openremote.model.event.bus.EventBus;-import org.openremote.manager.client.interop.keycloak.*;+import org.openremote.manager.client.interop.Consumer;+import org.openremote.manager.client.interop.keycloak.AuthToken;+import org.openremote.manager.client.interop.keycloak.Keycloak;+import org.openremote.manager.client.interop.keycloak.KeycloakCallback;+import org.openremote.manager.client.interop.keycloak.LogoutOptions;+import org.openremote.manager.shared.http.RequestParams;import org.openremote.model.Constants;+import org.openremote.model.event.bus.EventBus;-import java.util.function.Consumer;import java.util.logging.Logger;-public class SecurityServiceImpl implements SecurityService {+public class KeycloakSecurityService implements SecurityService {- private static final Logger LOG = Logger.getLogger(SecurityServiceImpl.class.getName());+ private static final Logger LOG = Logger.getLogger(KeycloakSecurityService.class.getName());protected final Keycloak keycloak;- @Inject- public SecurityServiceImpl(Keycloak keycloak,- CookieService cookieService,- EventBus eventBus) {+ public KeycloakSecurityService(Keycloak keycloak,+ CookieService cookieService,+ EventBus eventBus) {this.keycloak = keycloak;onAuthSuccess(() -> eventBus.dispatch(@@ -51,7 +53,7 @@ public class SecurityServiceImpl implements SecurityService {});// We update the refresh token in the background. The only other option would- // be to update the token before every request in request service. However, this+ // be to update the token before every request. However, this// will force asynchronous execution of all HTTP requests, which we don't want.Browser.getWindow().setInterval(() -> updateToken(Constants.ACCESS_TOKEN_LIFESPAN_SECONDS/2, // Token must be good for X more seconds@@ -61,13 +63,13 @@ public class SecurityServiceImpl implements SecurityService {}@Override- public void login() {- keycloak.login();+ public String getUsername() {+ return getParsedToken().getPreferredUsername();}@Override- public void login(LoginOptions options) {- keycloak.login(options);+ public String getFullName() {+ return getParsedToken().getName();}@Override@@ -79,21 +81,6 @@ public class SecurityServiceImpl implements SecurityService {keycloak.logout(opts);}- @Override- public void logout(LogoutOptions options) {- keycloak.logout(options);- }-- @Override- public void register() {- keycloak.register();- }-- @Override- public void register(LoginOptions options) {- keycloak.register(options);- }-@Overridepublic boolean isSuperUser() {return getAuthenticatedRealm().equals(Constants.MASTER_REALM) && hasRealmRole(Constants.REALM_ADMIN_ROLE);@@ -115,69 +102,42 @@ public class SecurityServiceImpl implements SecurityService {}@Override- public boolean isTokenExpired() {- return keycloak.isTokenExpired();+ public String getAuthenticatedRealm() {+ return keycloak.realm;}@Override- public boolean isTokenExpired(int minValiditySeconds) {- return keycloak.isTokenExpired(minValiditySeconds);+ public <OUT> void setCredentials(RequestParams<OUT> requestParams) {+ // TODO If the periodic refresh of token (see above) is not enough, this is where we could refresh+ requestParams.withBearerAuth(getToken());}@Override- public void clearToken() {- keycloak.clearToken();+ public String setCredentials(String serviceUrl) {+ // TODO If the periodic refresh of token (see above) is not enough, this is where we could refresh+ String authenticatedServiceUrl = serviceUrl+ + "?Auth-Realm=" + getAuthenticatedRealm()+ + "&Authorization=Bearer " + getToken();+ return authenticatedServiceUrl;}- @Override- public void onTokenExpired(Runnable fn) {- keycloak.onTokenExpired(new org.openremote.manager.client.interop.Runnable(){- @Override- public void run() {- fn.run();- }- });+ protected String getToken() {+ return keycloak.token;}- @Override- public void onAuthSuccess(Runnable fn) {- keycloak.onAuthSuccess = new org.openremote.manager.client.interop.Runnable(){- @Override- public void run() {- fn.run();- }- };+ protected AuthToken getParsedToken() {+ return keycloak.tokenParsed;}- @Override- public void onAuthLogout(Runnable fn) {- keycloak.onAuthLogout = new org.openremote.manager.client.interop.Runnable(){- @Override- public void run() {- fn.run();- }- };+ protected void onAuthSuccess(Runnable fn) {+ keycloak.onAuthSuccess = () -> fn.run();}- @Override- public void updateToken(Consumer<Boolean> successFn, Runnable errorFn) {- KeycloakCallback kcCallback = keycloak.updateToken();- kcCallback.success(new org.openremote.manager.client.interop.Consumer<Boolean>(){- @Override- public void accept(Boolean o) {- successFn.accept(o);- }- });- kcCallback.error(new org.openremote.manager.client.interop.Runnable(){- @Override- public void run() {- errorFn.run();- }- });+ protected void onAuthLogout(Runnable fn) {+ keycloak.onAuthLogout = () -> fn.run();}- @Override- public void updateToken(int minValiditySeconds, Consumer<Boolean> successFn, Runnable errorFn) {+ protected void updateToken(int minValiditySeconds, Consumer<Boolean> successFn, Runnable errorFn) {KeycloakCallback kcCallback = keycloak.updateToken(minValiditySeconds);kcCallback.success(new org.openremote.manager.client.interop.Consumer<Boolean>(){@Override@@ -192,24 +152,4 @@ public class SecurityServiceImpl implements SecurityService {}});}-- @Override- public String getAuthenticatedRealm() {- return keycloak.realm;- }-- @Override- public String getToken() {- return keycloak.token;- }-- @Override- public AuthToken getParsedToken() {- return keycloak.tokenParsed;- }-- @Override- public String getRefreshToken() {- return keycloak.refreshToken;- }}diff --git a/manager/client/src/main/java/org/openremote/manager/client/service/RequestServiceImpl.java b/manager/client/src/main/java/org/openremote/manager/client/service/RequestServiceImpl.javaindex 24ffcbaec..80b796390 100644--- a/manager/client/src/main/java/org/openremote/manager/client/service/RequestServiceImpl.java+++ b/manager/client/src/main/java/org/openremote/manager/client/service/RequestServiceImpl.java@@ -192,7 +192,7 @@ public class RequestServiceImpl implements RequestService {});- requestParams.withBearerAuth(securityService.getToken());+ securityService.setCredentials(requestParams);if (entityWriter != null) {requestParams.setEntityWriter(entityWriter);diff --git a/manager/client/src/main/java/org/openremote/manager/client/service/SecurityService.java b/manager/client/src/main/java/org/openremote/manager/client/service/SecurityService.javaindex 661e8dad8..352a7136c 100644--- a/manager/client/src/main/java/org/openremote/manager/client/service/SecurityService.java+++ b/manager/client/src/main/java/org/openremote/manager/client/service/SecurityService.java@@ -19,26 +19,16 @@*/package org.openremote.manager.client.service;-import org.openremote.manager.client.interop.keycloak.AuthToken;-import org.openremote.manager.client.interop.keycloak.LoginOptions;-import org.openremote.manager.client.interop.keycloak.LogoutOptions;--import java.util.function.Consumer;+import org.openremote.manager.shared.http.RequestParams;public interface SecurityService {- void login();+ String getUsername();- void login(LoginOptions options);+ String getFullName();void logout();- void logout(LogoutOptions options);-- void register();-- void register(LoginOptions options);-/*** @return <code>true</code> if the user is authenticated in the "master" realm and has the realm role "admin".*/@@ -50,27 +40,9 @@ public interface SecurityService {boolean hasResourceRoleOrIsSuperUser(String role, String resource);- boolean isTokenExpired();-- boolean isTokenExpired(int minValiditySeconds);-- void clearToken();-- void onTokenExpired(Runnable expiredFn);-- void onAuthSuccess(Runnable expiredFn);-- void onAuthLogout(Runnable expiredFn);-- void updateToken(Consumer<Boolean> successFn, Runnable errorFn);-- void updateToken(int minValiditySeconds, Consumer<Boolean> successFn, Runnable errorFn);-String getAuthenticatedRealm();- String getToken();-- AuthToken getParsedToken();+ <OUT> void setCredentials(RequestParams<OUT> requestParams);- String getRefreshToken();+ String setCredentials(String serviceUrl);}diff --git a/manager/client/src/main/java/org/openremote/manager/client/user/UserControlsPresenter.java b/manager/client/src/main/java/org/openremote/manager/client/user/UserControlsPresenter.javaindex dd8f34e77..96c1a18d2 100644--- a/manager/client/src/main/java/org/openremote/manager/client/user/UserControlsPresenter.java+++ b/manager/client/src/main/java/org/openremote/manager/client/user/UserControlsPresenter.java@@ -70,8 +70,8 @@ public class UserControlsPresenter implements UserControls.Presenter {protected void updateView() {view.setUserDetails(- environment.getSecurityService().getParsedToken().getPreferredUsername(),- environment.getSecurityService().getParsedToken().getName(),+ environment.getSecurityService().getUsername(),+ environment.getSecurityService().getFullName(),managerHistoryMapper.getToken(new UserAccountPlace()),environment.getSecurityService().hasResourceRole("manage-account", "account"));diff --git a/manager/client/src/main/webapp/index.html b/manager/client/src/main/webapp/index.htmlindex c203761af..6bb396e7a 100644--- a/manager/client/src/main/webapp/index.html+++ b/manager/client/src/main/webapp/index.html@@ -8,29 +8,12 @@<link rel="icon" type="image/png" href="/static/img/favicon.png"/><script src="/static/js/loader.js"></script>- <link rel="stylesheet" type="text/css" href="/static/css/loader.css" />-- <script src="/auth/js/keycloak.min.js"></script>+ <link rel="stylesheet" type="text/css" href="/static/css/loader.css"/>+ <script src="/static/js/auth.js"></script><script>- document.addEventListener("DOMContentLoaded", function (event) {- var keycloakConfig = {- url: '/auth',- realm: window.location.pathname.split('/')[1],- clientId: "openremote"- };- window.keycloak = Keycloak(keycloakConfig);- window.keycloak.init({onLoad: 'login-required'})- .success(function (authenticated) {- if (authenticated) {- setTimeout(function() {- startApplication();- }, 0);- } else {- window.keycloak.login();- }- })- .error(handleLoadError);+ document.addEventListener("DOMContentLoaded", function () {+ authenticate(startApplication, handleLoadError);});function startApplication() {@@ -56,7 +39,7 @@}).catch(handleLoadError);}- window.addEventListener('JSAPIReady', function() {+ window.addEventListener('JSAPIReady', function () {console.log("Loading application...");Promise.all([load.js("/static/gwt/Manager/Manager.nocache.js")@@ -65,7 +48,7 @@}).catch(handleLoadError);});- window.addEventListener('ManagerReady', function() {+ window.addEventListener('ManagerReady', function () {console.log("Application starting");handleLoadComplete();});@@ -73,7 +56,7 @@</script></head>-<body class="layout vertical loading">+<body class="layout vertical loading" onload="startLoading()"><iframe src="javascript:''"id="__gwt_historyFrame"diff --git a/manager/client/src/main/webapp/js/auth.js b/manager/client/src/main/webapp/js/auth.jsnew file mode 100644index 000000000..4e9594ec9--- /dev/null+++ b/manager/client/src/main/webapp/js/auth.js@@ -0,0 +1,169 @@+window.authenticate = function (successCallback, errorCallback) {+ Promise.all([+ load.js("/auth/js/keycloak.min.js")+ ]).then(function (e) {+ console.log("Keycloak available...");+ startKeycloakAuthentication(successCallback, errorCallback);+ }).catch(function () {+ console.log("Keycloak not available, falling back to basic authentication...");+ startBasicAuthentication(successCallback, errorCallback);+ })+};++window.startKeycloakAuthentication = function (successCallback, errorCallback) {+ var keycloakConfig = {+ url: '/auth',+ realm: window.location.pathname.split('/')[1],+ clientId: "openremote"+ };+ window.keycloak = Keycloak(keycloakConfig);+ window.keycloak.init({onLoad: 'login-required'})+ .success(function (authenticated) {+ if (authenticated) {+ console.log("Keycloak authentication successful...");+ successCallback();+ } else {+ console.log("Keycloak authentication failed, forcing login...");+ window.keycloak.login();+ }+ })+ .error(errorCallback);+};++window.startBasicAuthentication = function (successCallback, errorCallback) {+ Promise.all([+ load.js("/static/bower_components/webcomponentsjs/webcomponents-lite.min.js"),+ load.import("/static/bower_components/iron-flex-layout/iron-flex-layout-classes.html"),+ load.css("/static/bower_components/font-awesome/css/font-awesome.css"),++ load.import("/static/css/style.html"),+ load.import("/static/css/theme.html")+ ]).then(function () {+ console.log("Resources loaded for basic authentication...");+ setTimeout(handleLoadComplete, 0);+ var authForm = renderBasicAuthForm();+ document.body.appendChild(authForm);+ // Override submit button handler+ document.querySelector("#basicAuthForm [name='login']").onclick = function() {+ var username = document.querySelector("#basicAuthForm [name='username']").value;+ var password = document.querySelector("#basicAuthForm [name='password']").value;+ performBasicAuthentication(+ username,+ password,+ function (e) {+ if (e === true) {+ console.log("Basic authentication successful...");+ // Application can grab the credentials from window for its own requests+ window.basicAuthUsername = username;+ window.basicAuthPassword = password;+ document.body.removeChild(authForm);+ startLoading();+ successCallback();+ } else {+ console.log("Basic authentication failed, trying again");+ document.querySelector("#basicAuthForm .basicAuthMessage").style.display = "inherit";+ document.querySelector("#basicAuthForm .basicAuthMessageText").innerText = "Login failed, invalid username or password.";+ }+ },+ function (e) {+ alert("Error sending authentication to service, please try again later.");+ console.dir(e);+ }+ );+ return false;+ }+ }).catch(errorCallback);+};++window.renderBasicAuthForm = function () {+ var authForm = document.createElement("div");+ authForm.classList.add("flex", "layout", "vertical");+ authForm.id = "basicAuthForm";+ authForm.innerHTML =+ '<div class="flex layout vertical center-center">' ++ '<div class="layout horizontal center-center" style="margin: 1em;">' ++ '<a href="https://www.openremote.com/">' ++ '<svg style="pointer-events: none; display: block; width: 4em; height:4em; margin-right: 0.4em;" viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet">' ++ '<path fill="#C4D600" d="M11.93,21.851c-5.551,0-10.066-4.515-10.066-10.065h2.108c0,4.388,3.57,7.958,7.958,7.958 c4.387,0,7.958-3.57,7.958-7.958c0-4.388-3.57-7.958-7.958-7.958V1.72c5.55,0,10.066,4.517,10.066,10.066 C21.996,17.336,17.48,21.851,11.93,21.851L11.93,21.851z"/>' ++ '<path fill="#4E9D2D" d="M10.406,19.088c-1.95-0.406-3.626-1.549-4.717-3.215s-1.469-3.66-1.062-5.61 c0.407-1.951,1.55-3.626,3.217-4.718c1.667-1.092,3.659-1.469,5.61-1.062c4.027,0.84,6.62,4.799,5.779,8.825l-2.063-0.429 c0.603-2.889-1.257-5.73-4.147-6.333c-1.4-0.292-2.829-0.022-4.025,0.762C7.802,8.091,6.982,9.293,6.69,10.693 c-0.291,1.398-0.021,2.828,0.762,4.024c0.783,1.196,1.985,2.016,3.385,2.307L10.406,19.088L10.406,19.088z"/>' ++ '<path fill="#1D5632" d="M11.936,16.622c-0.082,0-0.164-0.001-0.245-0.004c-1.29-0.065-2.478-0.628-3.346-1.585 c-0.868-0.958-1.31-2.195-1.246-3.487l2.104,0.105c-0.036,0.728,0.214,1.427,0.704,1.967c0.488,0.54,1.16,0.858,1.888,0.894 c0.725,0.033,1.426-0.213,1.966-0.703c0.541-0.489,0.858-1.159,0.895-1.887c0.075-1.503-1.088-2.787-2.591-2.862l0.105-2.104 c2.664,0.132,4.724,2.406,4.592,5.07c-0.064,1.291-0.628,2.478-1.585,3.345C14.28,16.183,13.137,16.622,11.936,16.622L11.936,16.622 z"/>' ++ '</svg>' ++ '</a>' ++ '<div class="layout vertical">' ++ '<div class="or-HeadlineText" style="margin: 0; white-space: nowrap;"><span>Master</span></div>' ++ '<div class="or-HeadlineSub" style="margin-left: 0.2em;">OpenRemote Login</div></div>' ++ '</div>' ++ '<div class="basicAuthMessage layout horizontal center or-FormMessages error" style="display: none;">' ++ '<div class="or-MessagesIcon fa fa-warning"></div>' ++ '<span class="basicAuthMessageText"></span>' ++ '</div>' ++ '<form class="layout vertical or-Form">' ++ '<div class="layout horizontal center or-FormGroup">' ++ '<div class="or-FormLabel">' ++ '<label for="username">Username or email</label>' ++ '</div>' ++ '<div class="or-FormField">' ++ '<input autocomplete="off" autocapitalize="off" class="or-FormControl or-FormInputText" name="username" value="" type="text" autofocus/>' ++ '</div>' ++ '</div>' ++ '<div class="layout horizontal center or-FormGroup">' ++ '<div class="or-FormLabel">' ++ '<label for="password">Password</label>' ++ '</div>' ++ '<div class="or-FormField">' ++ '<input class="or-FormControl or-FormInputText" name="password" type="password" autocomplete="off"/>' ++ '</div>' ++ '</div>' ++ '<div class="layout horizontal center-center or-FormGroup">' ++ '<div>' ++ '<div>' ++ '</div>' ++ '</div>' ++ '<div class="or-FormField">' ++ '<input class="or-FormControl or-FormButtonPrimary or-PushButton" name="login" type="submit" value="Log in"/>' ++ '</div>' ++ '</div>' ++ '</form>' ++ '</div>';+ return authForm;+};++window.performBasicAuthentication = function (username, password, successCallback, errorCallback) {+ // Send a request with credentials to a resource that we know returns 200 or 401+ try {+ var x = new XMLHttpRequest();++ // TODO You all suck+ var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);+ var isChrome = !!window.chrome && !!window.chrome.webstore;+ if (isSafari) {+ // Must be async false or Safari will popup 401 dialog+ x.open("GET", "/master/asset/user/current", false);+ } else if (isChrome) {+ // Must set dummy URL username or Chrome will popup 401 dialog+ x.open("GET", "/master/asset/user/current", true, "dummy");+ } else {+ x.open("GET", "/master/asset/user/current", true);+ }++ var credentials = "Basic " + btoa(username + ":" + password);+ x.setRequestHeader("Authorization", credentials);++ x.onreadystatechange = function () {+ if (x.readyState > 3) {+ if (successCallback && x.status === 200) {+ successCallback(true);+ } else if (successCallback && x.status === 401) {+ successCallback(false);+ } else if (errorCallback) {+ errorCallback(x);+ }+ }+ };+ x.send()+ } catch (e) {+ if (errorCallback) {+ errorCallback(e);+ }+ }+};diff --git a/manager/client/src/main/webapp/js/loader.js b/manager/client/src/main/webapp/js/loader.jsindex 453fe95b3..3abdac322 100644--- a/manager/client/src/main/webapp/js/loader.js+++ b/manager/client/src/main/webapp/js/loader.js@@ -1,24 +1,33 @@window.defaultErrorMessage = "Service not available, please try again later.";-// Need this to find out if GWT superdev compilation failed, then abort loading...-window.checkGwtDebugInterval = window.setInterval(function() {- if (document.querySelectorAll("a[target='gwt_dev_mode_log']").length > 0) {- window.document.body.style.background = 'inherit';- window.document.body.style.opacity = "inherit";- window.document.body.style.transition = "inherit";- window.handleLoadComplete();+window.startLoading = function() {+ console.log("Start loading...");+ if (!window.document.body.classList.contains("loading")) {+ window.document.body.classList.add("loading");}-}, 500);+ // Need this to find out if GWT superdev compilation failed, then abort loading...+ window.clearInterval(window.checkGwtDebugInterval);+ window.checkGwtDebugInterval = window.setInterval(function() {+ if (document.querySelectorAll("a[target='gwt_dev_mode_log']").length > 0) {+ window.document.body.style.background = 'inherit';+ window.document.body.style.opacity = "inherit";+ window.document.body.style.transition = "inherit";+ window.handleLoadComplete();+ }+ }, 500);+};window.handleLoadError = function(reason) {+ console.log("Load error: " + reason);handleLoadComplete();window.document.body.innerHTML ="<div style='padding:1em;'><h1>Error starting application</h1><h5>Resource not loaded: " + reason + "</h5><h3>" + defaultErrorMessage + "</h3></div>";};window.handleLoadComplete = function() {+ console.log("Load complete...");window.document.body.classList.remove("loading");- window.clearInterval(window.checkGwtDebugInterval);+ window.checkGwtDebugInterval && window.clearInterval(window.checkGwtDebugInterval);};window.load = (function () {diff --git a/manager/rpi3.Dockerfile b/manager/rpi3.Dockerfileindex d28f7b157..6f0b09306 100644--- a/manager/rpi3.Dockerfile+++ b/manager/rpi3.Dockerfile@@ -3,8 +3,24 @@ FROM openremote/rpi-raspbian:latestENV LANG C.UTF-8RUN [ "cross-build-start" ]-RUN apt-get update && apt-get install -y openjdk-8-jdk-headless --no-install-recommends && rm -rf /var/lib/apt/lists/*-ENV JAVA_HOME /usr/lib/jvm/java-8-openjdk-armhf++# OpenJDK with slow interpreter JIT+#RUN apt-get update && apt-get install -y openjdk-8-jdk-headless --no-install-recommends && rm -rf /var/lib/apt/lists/*+#ENV JAVA_HOME /usr/lib/jvm/java-8-openjdk-armhf++# Oracle JDK with bad licensing - Make sure you understand the cost before using this in production!+RUN echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main" | tee /etc/apt/sources.list.d/webupd8team-java.list && \+ echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main" | tee -a /etc/apt/sources.list.d/webupd8team-java.list && \+ apt-key adv --keyserver keyserver.ubuntu.com --recv-keys EEA14886 && \+ apt-get update && \+ echo debconf shared/accepted-oracle-license-v1-1 select true | debconf-set-selections && \+ echo debconf shared/accepted-oracle-license-v1-1 seen true | debconf-set-selections && \+ DEBIAN_FRONTEND=noninteractive apt-get install -y --force-yes oracle-java8-installer oracle-java8-set-default && \+ rm -rf /var/cache/oracle-jdk8-installer && \+ apt-get clean && \+ rm -rf /var/lib/apt/lists/*+ENV JAVA_HOME /usr/lib/jvm/java-8-oracle+RUN [ "cross-build-end" ]ENV MANAGER_DOCROOT webappdiff --git a/manager/server/src/main/java/org/openremote/manager/server/Main.java b/manager/server/src/main/java/org/openremote/manager/server/Main.javaindex 48d820402..2643f0dc3 100644--- a/manager/server/src/main/java/org/openremote/manager/server/Main.java+++ b/manager/server/src/main/java/org/openremote/manager/server/Main.java@@ -24,23 +24,23 @@ import org.openremote.container.Container;import org.openremote.container.ContainerService;import org.openremote.container.message.MessageBrokerService;import org.openremote.container.message.MessageBrokerSetupService;-import org.openremote.container.persistence.PersistenceService;import org.openremote.container.timer.TimerService;import org.openremote.manager.server.agent.AgentService;import org.openremote.manager.server.apps.ConsoleAppService;import org.openremote.manager.server.asset.AssetAttributeLinkingService;import org.openremote.manager.server.asset.AssetProcessingService;import org.openremote.manager.server.asset.AssetStorageService;+import org.openremote.manager.server.concurrent.ManagerExecutorService;import org.openremote.manager.server.datapoint.AssetDatapointService;import org.openremote.manager.server.event.ClientEventService;import org.openremote.manager.server.i18n.I18NService;import org.openremote.manager.server.map.MapService;import org.openremote.manager.server.notification.NotificationService;+import org.openremote.manager.server.persistence.ManagerPersistenceService;import org.openremote.manager.server.rules.RulesService;import org.openremote.manager.server.rules.RulesetStorageService;import org.openremote.manager.server.security.ManagerIdentityService;import org.openremote.manager.server.setup.SetupService;-import org.openremote.manager.server.concurrent.ManagerExecutorService;import org.openremote.manager.server.simulator.SimulatorService;import org.openremote.manager.server.web.ManagerWebService;@@ -58,7 +58,7 @@ public class Main {new TimerService(),new ManagerExecutorService(),new I18NService(),- new PersistenceService(),+ new ManagerPersistenceService(),new MessageBrokerSetupService(),new ManagerIdentityService(),new SetupService(),diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.javaindex 4b4e17b55..aea0ecc65 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java@@ -176,7 +176,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSerreturn false;}- boolean isRestrictedUser = identityService.isRestrictedUser(auth.getUserId());+ boolean isRestrictedUser = identityService.getIdentityProvider().isRestrictedUser(auth.getUserId());// Client can subscribe to several assetsfor (String assetId : filter.getEntityId()) {diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetRoute.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetRoute.javaindex 392eb5de3..92057d19c 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetRoute.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetRoute.java@@ -174,7 +174,7 @@ public final class AssetRoute {}// Check restricted user- if (identityService.isRestrictedUser(authContext.getUserId())) {+ if (identityService.getIdentityProvider().isRestrictedUser(authContext.getUserId())) {// Must be asset linked to userif (!assetStorageService.isUserAsset(authContext.getUserId(), event.getEntityId())) {throw new AssetProcessingException(Reason.INSUFFICIENT_ACCESS);diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.javaindex 4e85b8671..b0c76c6d0 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java@@ -95,7 +95,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicreturn true;// Restricted users get nothing (they don't have asset trees, just a list of linked assets)- if (managerIdentityService.isRestrictedUser(auth.getUserId()))+ if (managerIdentityService.getIdentityProvider().isRestrictedUser(auth.getUserId()))return false;// User must have role@@ -194,7 +194,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicServerAsset asset = find(event.getAssetId(),true,- managerIdentityService.isRestrictedUser(authContext.getUserId()) // Restricted users get filtered state+ managerIdentityService.getIdentityProvider().isRestrictedUser(authContext.getUserId()) // Restricted users get filtered state);if (asset != null) {replyWithAttributeEvents(sessionKey, asset, event.getAttributeNames());@@ -409,10 +409,12 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicString whereClause = buildWhereClause(query, binders);sb.append(whereClause);sb.append(buildOrderByString(query));+ String querySql = sb.toString();return em.unwrap(Session.class).doReturningWork(new AbstractReturningWork<List<ServerAsset>>() {@Overridepublic List<ServerAsset> execute(Connection connection) throws SQLException {- PreparedStatement st = connection.prepareStatement(sb.toString());+ LOG.fine("Executing: " + querySql);+ PreparedStatement st = connection.prepareStatement(querySql);for (ParameterBinder binder : binders) {binder.accept(st);}diff --git a/manager/server/src/main/java/org/openremote/manager/server/persistence/ManagerPersistenceService.java b/manager/server/src/main/java/org/openremote/manager/server/persistence/ManagerPersistenceService.javanew file mode 100644index 000000000..0ed83ec29--- /dev/null+++ b/manager/server/src/main/java/org/openremote/manager/server/persistence/ManagerPersistenceService.java@@ -0,0 +1,53 @@+/*+ * 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.manager.server.persistence;++import org.openremote.container.Container;+import org.openremote.container.persistence.PersistenceService;+import org.openremote.manager.server.security.ManagerIdentityService;+import org.openremote.model.util.TextUtil;++import java.util.ArrayList;+import java.util.List;++public class ManagerPersistenceService extends PersistenceService {++ @Override+ public void start(Container container) throws Exception {++ // Before schema is generated, execute this+ persistenceUnitProperties.put("javax.persistence.schema-generation.create-source", "script-then-metadata");+ persistenceUnitProperties.put("javax.persistence.schema-generation.create-script-source", "Extensions.sql");++ // After schema is generated, execute this+ List<String> importFiles = new ArrayList<>();+ if (!container.getService(ManagerIdentityService.class).isKeycloakEnabled()) {+ importFiles.add("BasicIdentityProvider.sql");+ }+ importFiles.add("GetAssetTreePath.sql");+ importFiles.add("Constraints.sql");+ persistenceUnitProperties.put(+ "hibernate.hbm2ddl.import_files",+ TextUtil.toCommaSeparated(importFiles.toArray(new String[importFiles.size()]))+ );++ super.start(container);+ }+}diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.javaindex 1bc8bd5ac..50cd34426 100644--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java@@ -714,7 +714,7 @@ public class RulesEngine<T extends Ruleset> {@Overridepublic void storeAndNotify(String userId, AlertNotification alert) {if (TenantRuleset.class.isAssignableFrom(rulesetType)) {- boolean userIsInTenant = identityService.isUserInTenant(userId, id);+ boolean userIsInTenant = identityService.getIdentityProvider().isUserInTenant(userId, id);if (!userIsInTenant) {throw new IllegalArgumentException("User not in tenant: " + id);}diff --git a/manager/server/src/main/java/org/openremote/manager/server/security/ManagerBasicIdentityProvider.java b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerBasicIdentityProvider.javanew file mode 100644index 000000000..fa2d075e6--- /dev/null+++ b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerBasicIdentityProvider.java@@ -0,0 +1,212 @@+/*+ * 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.manager.server.security;++import io.undertow.security.idm.Account;+import org.openremote.container.Container;+import org.openremote.container.security.AuthContext;+import org.openremote.container.security.basic.BasicAuthContext;+import org.openremote.container.security.basic.BasicIdentityProvider;+import org.openremote.container.security.basic.PasswordStorage;+import org.openremote.container.web.ClientRequestInfo;+import org.openremote.manager.server.persistence.ManagerPersistenceService;+import org.openremote.manager.shared.security.*;+import org.openremote.model.Constants;+import org.openremote.model.asset.Asset;++import javax.persistence.NoResultException;+import javax.persistence.NonUniqueResultException;+import java.security.Principal;+import java.util.Objects;+import java.util.Set;+import java.util.logging.Logger;++public class ManagerBasicIdentityProvider extends BasicIdentityProvider implements ManagerIdentityProvider {++ private static final Logger LOG = Logger.getLogger(ManagerBasicIdentityProvider.class.getName());++ final protected ManagerPersistenceService persistenceService;++ final protected Tenant masterTenant = new Tenant(Constants.MASTER_REALM, Constants.MASTER_REALM, "Master", true);++ public ManagerBasicIdentityProvider(Container container) {+ this.persistenceService = container.getService(ManagerPersistenceService.class);+ }++ @Override+ protected Account verifyAccount(String username, char[] password) {+ LOG.fine("Authentication attempt, querying user: " + username);+ Object[] idAndPassword = persistenceService.doReturningTransaction(em -> {+ try {+ return (Object[]) em.createNativeQuery(+ "select U.ID, U.PASSWORD from USER_ENTITY U where U.USERNAME = :username"+ ).setParameter("username", username).getSingleResult();+ } catch (NoResultException | NonUniqueResultException ex) {+ return null;+ }+ }+ );+ if (idAndPassword == null) {+ LOG.fine("Authentication failed, no such user: " + username);+ return null;+ }+ LOG.fine("Authentication attempt, verifying password: " + username);+ if (!PasswordStorage.verifyPassword(password, idAndPassword[1].toString())) {+ LOG.fine("Authentication failed, invalid password: " + username);+ return null;+ }++ LOG.fine("Authentication successful: " + username);+ final BasicAuthContext principal = new BasicAuthContext(Constants.MASTER_REALM, idAndPassword[0].toString(), username);+ return new Account() {+ @Override+ public Principal getPrincipal() {+ return principal;+ }++ @Override+ public Set<String> getRoles() {+ return ClientRole.ALL_ROLES;+ }+ };+ }++ @Override+ public User[] getUsers(ClientRequestInfo clientRequestInfo, String realm) {+ return new User[0];+ }++ @Override+ public User getUser(ClientRequestInfo clientRequestInfo, String realm, String userId) {+ return null;+ }++ @Override+ public void updateUser(ClientRequestInfo clientRequestInfo, String realm, String userId, User user) {++ }++ @Override+ public void createUser(ClientRequestInfo clientRequestInfo, String realm, User user) {++ }++ @Override+ public void deleteUser(ClientRequestInfo clientRequestInfo, String realm, String userId) {++ }++ @Override+ public void resetPassword(ClientRequestInfo clientRequestInfo, String realm, String userId, Credential credential) {++ }++ @Override+ public Role[] getRoles(ClientRequestInfo clientRequestInfo, String realm, String userId) {+ return new Role[0];+ }++ @Override+ public void updateRoles(ClientRequestInfo clientRequestInfo, String realm, String userId, Role[] roles) {++ }++ @Override+ public boolean isMasterRealmAdmin(ClientRequestInfo clientRequestInfo, String userId) {+ return false;+ }++ @Override+ public void setRestrictedUser(String userId, boolean restricted) {++ }++ @Override+ public boolean isRestrictedUser(String userId) {+ return false;+ }++ @Override+ public boolean isUserInTenant(String userId, String realmId) {+ // TODO+ return true;+ }++ @Override+ public Tenant[] getTenants(ClientRequestInfo clientRequestInfo) {+ return new Tenant[]{masterTenant};+ }++ @Override+ public Tenant getTenantForRealm(String realm) {+ return Objects.equals(realm, Constants.MASTER_REALM) ? masterTenant : null;+ }++ @Override+ public Tenant getTenantForRealmId(String realmId) {+ return Objects.equals(realmId, Constants.MASTER_REALM) ? masterTenant : null;+ }++ @Override+ public void updateTenant(ClientRequestInfo clientRequestInfo, String realm, Tenant tenant) {+ throw new UnsupportedOperationException("This provider does not support multiple tenants");++ }++ @Override+ public void createTenant(ClientRequestInfo clientRequestInfo, Tenant tenant) {+ throw new UnsupportedOperationException("This provider does not support multiple tenants");+ }++ @Override+ public void createTenant(ClientRequestInfo clientRequestInfo, Tenant tenant, TenantEmailConfig emailConfig) {+ throw new UnsupportedOperationException("This provider does not support multiple tenants");+ }++ @Override+ public void deleteTenant(ClientRequestInfo clientRequestInfo, String realm) {+ throw new UnsupportedOperationException("This provider does not support multiple tenants");+ }++ @Override+ public boolean isTenantActiveAndAccessible(AuthContext authContext, Tenant tenant) {+ return Objects.equals(tenant.getId(), Constants.MASTER_REALM);+ }++ @Override+ public boolean isTenantActiveAndAccessible(AuthContext authContext, Asset asset) {+ return Objects.equals(asset.getRealmId(), Constants.MASTER_REALM);+ }++ @Override+ public String[] getActiveTenantIds() {+ return new String[]{Constants.MASTER_REALM};+ }++ @Override+ public boolean isActiveTenant(String realmId) {+ return Objects.equals(realmId, Constants.MASTER_REALM);+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{}";+ }+}diff --git a/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityProvider.java b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityProvider.javaindex 66dd4af29..67ada515d 100644--- a/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityProvider.java+++ b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityProvider.java@@ -49,6 +49,12 @@ public interface ManagerIdentityProvider extends IdentityProvider {boolean isMasterRealmAdmin(ClientRequestInfo clientRequestInfo, String userId);+ void setRestrictedUser(String userId, boolean restricted);++ boolean isRestrictedUser(String userId);++ boolean isUserInTenant(String userId, String realmId);+Tenant[] getTenants(ClientRequestInfo clientRequestInfo);Tenant getTenantForRealm(String realm);diff --git a/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.javaindex c34ee26b9..f380820e7 100644--- a/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java@@ -24,10 +24,19 @@ import org.openremote.container.persistence.PersistenceService;import org.openremote.container.security.IdentityService;import org.openremote.container.timer.TimerService;import org.openremote.container.web.WebService;-import org.openremote.manager.shared.security.User;++import java.util.Locale;+import java.util.logging.Logger;++import static org.openremote.container.util.MapAccess.getString;public class ManagerIdentityService extends IdentityService {+ private static final Logger LOG = Logger.getLogger(ManagerIdentityService.class.getName());++ public static final String MANAGER_IDENTITY_PROVIDER = "MANAGER_IDENTITY_PROVIDER";+ public static final String MANAGER_IDENTITY_PROVIDER_DEFAULT = "keycloak";+protected PersistenceService persistenceService;protected ManagerIdentityProvider identityProvider;@@ -44,8 +53,19 @@ public class ManagerIdentityService extends IdentityService {new UserResourceImpl(container.getService(TimerService.class), this));- // TODO Configurable provider- this.identityProvider = new ManagerKeycloakProvider(getExternalServerUri(), container);+ String identityProviderType = getString(container.getConfig(), MANAGER_IDENTITY_PROVIDER, MANAGER_IDENTITY_PROVIDER_DEFAULT);+ switch (identityProviderType.toLowerCase(Locale.ROOT)) {+ case "keycloak":+ LOG.info("Enabling Keycloak identity provider");+ this.identityProvider = new ManagerKeycloakIdentityProvider(getExternalServerUri(), container);+ break;+ case "basic":+ LOG.info("Enabling basic identity provider");+ this.identityProvider = new ManagerBasicIdentityProvider(container);+ break;+ default:+ throw new UnsupportedOperationException("Unknown identity provider: " + identityProviderType);+ }}@Override@@ -53,47 +73,10 @@ public class ManagerIdentityService extends IdentityService {return identityProvider;}- // TODO Should all User operations move to ManagerIdentityProvider?-- public boolean isRestrictedUser(String userId) {- UserConfiguration userConfiguration = getUserConfiguration(userId);- return userConfiguration.isRestricted();- }-- public void setRestrictedUser(String userId, boolean restricted) {- UserConfiguration userConfiguration = getUserConfiguration(userId);- userConfiguration.setRestricted(restricted);- mergeUserConfiguration(userConfiguration);- }-- protected UserConfiguration getUserConfiguration(String userId) {- UserConfiguration userConfiguration = persistenceService.doReturningTransaction(em -> em.find(UserConfiguration.class, userId));- if (userConfiguration == null) {- userConfiguration = new UserConfiguration(userId);- userConfiguration = mergeUserConfiguration(userConfiguration);- }- return userConfiguration;- }-- protected UserConfiguration mergeUserConfiguration(UserConfiguration userConfiguration) {- if (userConfiguration.getUserId() == null || userConfiguration.getUserId().length() == 0) {- throw new IllegalArgumentException("User ID must be set on: " + userConfiguration);- }- return persistenceService.doReturningTransaction(em -> em.merge(userConfiguration));- }-- public boolean isUserInTenant(String userId, String realmId) {- return persistenceService.doReturningTransaction(em -> {- User user = em.find(User.class, userId);- return (user != null&& realmId.equals(user.getRealmId()));- });- }--@Overridepublic String toString() {return getClass().getSimpleName() + "{" ++ "identityProvider=" + identityProvider +'}';}-}diff --git a/manager/server/src/main/java/org/openremote/manager/server/security/ManagerKeycloakProvider.java b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerKeycloakIdentityProvider.javasimilarity index 89%rename from manager/server/src/main/java/org/openremote/manager/server/security/ManagerKeycloakProvider.javarename to manager/server/src/main/java/org/openremote/manager/server/security/ManagerKeycloakIdentityProvider.javaindex f967dd2aa..a8c084eee 100644--- a/manager/server/src/main/java/org/openremote/manager/server/security/ManagerKeycloakProvider.java+++ b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerKeycloakIdentityProvider.java@@ -50,9 +50,9 @@ import java.util.logging.Logger;import static org.openremote.manager.server.util.JsonUtil.convert;import static org.openremote.model.Constants.*;-public class ManagerKeycloakProvider extends KeycloakIdentityProvider implements ManagerIdentityProvider {+public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider implements ManagerIdentityProvider {- private static final Logger LOG = Logger.getLogger(ManagerKeycloakProvider.class.getName());+ private static final Logger LOG = Logger.getLogger(ManagerKeycloakIdentityProvider.class.getName());final boolean devMode;final protected PersistenceService persistenceService;@@ -60,7 +60,7 @@ public class ManagerKeycloakProvider extends KeycloakIdentityProvider implementsfinal protected MessageBrokerService messageBrokerService;final protected ClientEventService clientEventService;- public ManagerKeycloakProvider(UriBuilder externalServerUri, Container container) {+ public ManagerKeycloakIdentityProvider(UriBuilder externalServerUri, Container container) {super(KEYCLOAK_CLIENT_ID, externalServerUri, container);this.devMode = container.isDevMode();@@ -329,6 +329,42 @@ public class ManagerKeycloakProvider extends KeycloakIdentityProvider implements});}+ @Override+ public boolean isRestrictedUser(String userId) {+ UserConfiguration userConfiguration = getUserConfiguration(userId);+ return userConfiguration.isRestricted();+ }++ @Override+ public void setRestrictedUser(String userId, boolean restricted) {+ UserConfiguration userConfiguration = getUserConfiguration(userId);+ userConfiguration.setRestricted(restricted);+ mergeUserConfiguration(userConfiguration);+ }++ protected UserConfiguration getUserConfiguration(String userId) {+ UserConfiguration userConfiguration = persistenceService.doReturningTransaction(em -> em.find(UserConfiguration.class, userId));+ if (userConfiguration == null) {+ userConfiguration = new UserConfiguration(userId);+ userConfiguration = mergeUserConfiguration(userConfiguration);+ }+ return userConfiguration;+ }++ protected UserConfiguration mergeUserConfiguration(UserConfiguration userConfiguration) {+ if (userConfiguration.getUserId() == null || userConfiguration.getUserId().length() == 0) {+ throw new IllegalArgumentException("User ID must be set on: " + userConfiguration);+ }+ return persistenceService.doReturningTransaction(em -> em.merge(userConfiguration));+ }++ @Override+ public boolean isUserInTenant(String userId, String realmId) {+ return persistenceService.doReturningTransaction(em -> {+ User user = em.find(User.class, userId);+ return (user != null && realmId.equals(user.getRealmId()));+ });+ }public void configureRealm(RealmRepresentation realmRepresentation, TenantEmailConfig emailConfig) {configureRealm(realmRepresentation, Constants.ACCESS_TOKEN_LIFESPAN_SECONDS);@@ -387,4 +423,8 @@ public class ManagerKeycloakProvider extends KeycloakIdentityProvider implements);}+ @Override+ public String toString() {+ return getClass().getSimpleName() + "{}";+ }}diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/AbstractKeycloakSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/AbstractKeycloakSetup.javaindex 9fdfd329b..aec778651 100644--- a/manager/server/src/main/java/org/openremote/manager/server/setup/AbstractKeycloakSetup.java+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/AbstractKeycloakSetup.java@@ -26,7 +26,7 @@ import org.keycloak.representations.idm.ClientRepresentation;import org.openremote.container.Container;import org.openremote.container.security.AuthForm;import org.openremote.manager.server.security.ManagerIdentityService;-import org.openremote.manager.server.security.ManagerKeycloakProvider;+import org.openremote.manager.server.security.ManagerKeycloakIdentityProvider;import org.openremote.manager.shared.security.TenantEmailConfig;import static org.openremote.container.util.MapAccess.getBoolean;@@ -58,7 +58,7 @@ public abstract class AbstractKeycloakSetup implements Setup {public static final String SETUP_KEYCLOAK_EMAIL_FROM_DEFAULT = "[email protected]";final protected ManagerIdentityService identityService;- final protected ManagerKeycloakProvider keycloakProvider;+ final protected ManagerKeycloakIdentityProvider keycloakProvider;final protected SetupService setupService;final protected String accessToken;final protected RealmResource masterRealmResource;@@ -68,7 +68,7 @@ public abstract class AbstractKeycloakSetup implements Setup {public AbstractKeycloakSetup(Container container) {this.identityService = container.getService(ManagerIdentityService.class);- this.keycloakProvider = ((ManagerKeycloakProvider)identityService.getIdentityProvider());+ this.keycloakProvider = ((ManagerKeycloakIdentityProvider)identityService.getIdentityProvider());this.setupService = container.getService(SetupService.class);@@ -97,7 +97,7 @@ public abstract class AbstractKeycloakSetup implements Setup {}}- public ManagerKeycloakProvider getKeycloakProvider() {+ public ManagerKeycloakIdentityProvider getKeycloakProvider() {return keycloakProvider;}diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/SchemaExporter.java b/manager/server/src/main/java/org/openremote/manager/server/setup/SchemaExporter.javaindex 594f9c247..edd5ae148 100644--- a/manager/server/src/main/java/org/openremote/manager/server/setup/SchemaExporter.java+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/SchemaExporter.java@@ -22,6 +22,7 @@ package org.openremote.manager.server.setup;import org.openremote.container.Container;import org.openremote.container.persistence.Database;import org.openremote.container.persistence.PersistenceService;+import org.openremote.manager.server.persistence.ManagerPersistenceService;import javax.persistence.Persistence;import java.io.File;@@ -44,7 +45,7 @@ public class SchemaExporter {File schemaFile = new File(args[0]);Container container = new Container(- new PersistenceService() {+ new ManagerPersistenceService() {@Overrideprotected void openDatabase(Container container, Database database) {diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/BasicIdentityDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/BasicIdentityDemoSetup.javanew file mode 100644index 000000000..7ba8b7ce9--- /dev/null+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/BasicIdentityDemoSetup.java@@ -0,0 +1,77 @@+/*+ * 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.manager.server.setup.builtin;++import com.fasterxml.uuid.Generators;+import org.hibernate.Session;+import org.openremote.container.Container;+import org.openremote.container.security.basic.PasswordStorage;+import org.openremote.manager.server.persistence.ManagerPersistenceService;+import org.openremote.manager.server.security.ManagerIdentityService;+import org.openremote.manager.server.setup.Setup;+import org.openremote.manager.shared.security.Tenant;+import org.openremote.model.Constants;++import java.sql.PreparedStatement;++/**+ * We have the following demo users:+ * <ul>+ * <li><code>admin</code> - The superuser in the "master" realm with all access</li>+ * </ul>+ */+public class BasicIdentityDemoSetup implements Setup {++ public static final String SETUP_BASIC_IDENTITY_ADMIN_PASSWORD = "SETUP_BASIC_IDENTITY_ADMIN_PASSWORD";+ public static final String SETUP_BASIC_IDENTITY_ADMIN_PASSWORD_DEFAULT = "secret";++ final protected ManagerPersistenceService persistenceService;+ final protected ManagerIdentityService identityService;+ final protected String demoAdminPassword;++ public Tenant masterTenant;++ public BasicIdentityDemoSetup(Container container) {+ this.persistenceService = container.getService(ManagerPersistenceService.class);+ this.identityService = container.getService(ManagerIdentityService.class);++ this.demoAdminPassword = container.getConfig().getOrDefault(SETUP_BASIC_IDENTITY_ADMIN_PASSWORD, SETUP_BASIC_IDENTITY_ADMIN_PASSWORD_DEFAULT);+ }++ @Override+ public void execute() throws Exception {++ // Tenants+ masterTenant = identityService.getIdentityProvider().getTenantForRealm(Constants.MASTER_REALM);++ // Users+++ persistenceService.doTransaction(em -> em.unwrap(Session.class).doWork(connection -> {+ String sql = "insert into USER_ENTITY(ID, REALM_ID, USERNAME, PASSWORD, ENABLED) values (?, 'master', 'admin', ?, true)";+ PreparedStatement st = connection.prepareStatement(sql);+ st.setString(1, Generators.randomBasedGenerator().generate().toString());+ st.setString(2, PasswordStorage.createHash(demoAdminPassword));+ st.executeUpdate();+ st.close();+ }));++ }+}diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/BasicIdentityInitSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/BasicIdentityInitSetup.javanew file mode 100644index 000000000..70ad37b24--- /dev/null+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/BasicIdentityInitSetup.java@@ -0,0 +1,52 @@+/*+ * 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.manager.server.setup.builtin;++import org.hibernate.Session;+import org.openremote.container.Container;+import org.openremote.manager.server.persistence.ManagerPersistenceService;+import org.openremote.manager.server.setup.Setup;++import java.sql.PreparedStatement;++public class BasicIdentityInitSetup implements Setup {++ final protected ManagerPersistenceService persistenceService;++ public BasicIdentityInitSetup(Container container) {+ this.persistenceService = container.getService(ManagerPersistenceService.class);+ }++ @Override+ public void execute() {+ // Configure the master realm+ persistenceService.doTransaction(em -> em.unwrap(Session.class).doWork(connection -> {+ String sql = "insert into REALM(ID, NAME, ENABLED) values ('master', 'master', true)";+ PreparedStatement st = connection.prepareStatement(sql);+ st.executeUpdate();+ st.close();++ sql = "insert into REALM_ATTRIBUTE(REALM_ID, NAME, VALUE) values ('master', 'displayName', 'Master')";+ st = connection.prepareStatement(sql);+ st.executeUpdate();+ st.close();+ }));+ }+}diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/BuiltinSetupTasks.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/BuiltinSetupTasks.javaindex b5a5ba579..72ea801e9 100644--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/BuiltinSetupTasks.java+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/BuiltinSetupTasks.java@@ -20,6 +20,7 @@package org.openremote.manager.server.setup.builtin;import org.openremote.container.Container;+import org.openremote.manager.server.security.ManagerIdentityService;import org.openremote.manager.server.setup.AbstractSetupTasks;import org.openremote.manager.server.setup.Setup;@@ -74,23 +75,36 @@ public class BuiltinSetupTasks extends AbstractSetupTasks {// If importing demo assets we have to import demo usersboolean importDemoUsers = importDemoAssets || getBoolean(container.getConfig(), SETUP_IMPORT_DEMO_USERS, container.isDevMode());- if (cleanDatabase) {- addTask(new ManagerCleanSetup(container));- addTask(new KeycloakCleanSetup(container));- addTask(new KeycloakInitSetup(container));- addTask(new ManagerInitSetup(container));- }-- if (importDemoUsers) {- addTask(new KeycloakDemoSetup(container));- }-- if (importDemoAssets) {- addTask(new ManagerDemoSetup(container, importDemoScenes));- }-- if (importDemoRules) {- addTask(new RulesDemoSetup(container));+ // Basic vs Keycloak identity provider+ if (container.getService(ManagerIdentityService.class).isKeycloakEnabled()) {+ if (cleanDatabase) {+ addTask(new ManagerCleanSetup(container));+ addTask(new KeycloakCleanSetup(container));+ addTask(new KeycloakInitSetup(container));+ addTask(new ManagerInitSetup(container));+ }++ if (importDemoUsers) {+ addTask(new KeycloakDemoSetup(container));+ }++ if (importDemoAssets) {+ addTask(new ManagerDemoSetup(container, importDemoScenes));+ }++ if (importDemoRules) {+ addTask(new RulesDemoSetup(container));+ }+ } else {+ if (cleanDatabase) {+ addTask(new ManagerCleanSetup(container));+ addTask(new ManagerInitSetup(container));+ addTask(new BasicIdentityInitSetup(container));+ }++ if (importDemoUsers) {+ addTask(new BasicIdentityDemoSetup(container));+ }}return getTasks();diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.javaindex 127e4fa5c..8a6a53f8e 100644--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java@@ -41,7 +41,6 @@ import java.time.LocalDateTime;import java.time.ZoneId;import java.time.ZonedDateTime;import java.util.Arrays;-import java.util.Date;import java.util.List;import static org.openremote.model.asset.AssetMeta.*;@@ -525,7 +524,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {// ################################ Link demo users and assets ###################################- identityService.setRestrictedUser(keycloakDemoSetup.testuser3Id, true);+ identityService.getIdentityProvider().setRestrictedUser(keycloakDemoSetup.testuser3Id, true);assetStorageService.storeUserAsset(keycloakDemoSetup.testuser3Id, apartment1Id);assetStorageService.storeUserAsset(keycloakDemoSetup.testuser3Id, apartment1LivingroomId);assetStorageService.storeUserAsset(keycloakDemoSetup.testuser3Id, apartment2Id);diff --git a/manager/server/src/main/java/org/openremote/manager/server/web/ManagerWebResource.java b/manager/server/src/main/java/org/openremote/manager/server/web/ManagerWebResource.javaindex 506264198..f1535358c 100644--- a/manager/server/src/main/java/org/openremote/manager/server/web/ManagerWebResource.java+++ b/manager/server/src/main/java/org/openremote/manager/server/web/ManagerWebResource.java@@ -36,7 +36,7 @@ public class ManagerWebResource extends WebResource {}public boolean isRestrictedUser() {- return identityService.isRestrictedUser(getUserId());+ return identityService.getIdentityProvider().isRestrictedUser(getUserId());}public Tenant getAuthenticatedTenant() {diff --git a/manager/server/src/main/resources/BasicIdentityProvider.sql b/manager/server/src/main/resources/BasicIdentityProvider.sqlnew file mode 100644index 000000000..f5a9d7a83--- /dev/null+++ b/manager/server/src/main/resources/BasicIdentityProvider.sql@@ -0,0 +1,29 @@+drop table if exists USER_ENTITY;+drop table if exists REALM_ATTRIBUTE;+drop table if exists REALM;++create table REALM (+ ID varchar(36) not null primary key,+ NAME varchar(255) unique not null,+ ENABLED boolean default false not null,+ NOT_BEFORE integer+);++create table REALM_ATTRIBUTE (+ NAME varchar(255) not null,+ VALUE varchar(255),+ REALM_ID varchar(36) not null references REALM,+ primary key (NAME, REALM_ID)+);++create table USER_ENTITY (+ ID varchar(36) not null primary key,+ REALM_ID varchar(255) not null,+ USERNAME varchar(255) not null,+ PASSWORD varchar(255) not null,+ FIRST_NAME varchar(255),+ LAST_NAME varchar(255),+ EMAIL varchar(255),+ ENABLED boolean default false not null,+ constraint USER_ENTITY_UNIQUE unique (REALM_ID, USERNAME)+);diff --git a/manager/server/src/main/resources/META-INF/persistence.xml b/manager/server/src/main/resources/META-INF/persistence.xmlindex 81547bf7b..ef1a06bac 100644--- a/manager/server/src/main/resources/META-INF/persistence.xml+++ b/manager/server/src/main/resources/META-INF/persistence.xml@@ -31,11 +31,6 @@<property name="hibernate.archive.autodetection" value="none"/><property name="hibernate.current_session_context_class" value="thread"/><property name="hibernate.hbm2ddl.import_files_sql_extractor" value="org.openremote.container.persistence.EnhancedImportSqlCommandExtractor"/>- <property name="javax.persistence.schema-generation.create-source" value="script-then-metadata"/>- <!-- Before the schema is created -->- <property name="javax.persistence.schema-generation.create-script-source" value="Extensions.sql"/>- <!-- After the schema is created -->- <property name="hibernate.hbm2ddl.import_files" value="GetAssetTreePath.sql, Constraints.sql"/></properties></persistence-unit>diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/security/ClientRole.java b/manager/shared/src/main/java/org/openremote/manager/shared/security/ClientRole.javaindex bc87d4ee3..2352df421 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/security/ClientRole.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/security/ClientRole.java@@ -22,7 +22,9 @@ package org.openremote.manager.shared.security;import org.keycloak.representations.idm.RoleRepresentation;import java.util.ArrayList;+import java.util.HashSet;import java.util.List;+import java.util.Set;/*** Roles available for our client application on Keycloak.@@ -55,6 +57,15 @@ public enum ClientRole {WRITE_RULES});+ // Only individual roles, not composites+ public static final Set<String> ALL_ROLES = new HashSet<String>() {{+ for (ClientRole clientRole : values()) {+ if (clientRole.composites == null) {+ add(clientRole.value);+ }+ }+ }};+final protected String value;final protected String description;final protected ClientRole[] composites;diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/security/Tenant.java b/manager/shared/src/main/java/org/openremote/manager/shared/security/Tenant.javaindex 16df830a3..6e8a5f422 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/security/Tenant.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/security/Tenant.java@@ -31,7 +31,7 @@ import javax.validation.constraints.Pattern;import javax.validation.constraints.Size;/**- * This can be used (among other things) to query the Keycloak REALM table in JPA queries.+ * This can be used (among other things) to query the REALM table in JPA queries.*/@Entity@Subselect("select * from REALM") // Map this immutable to an SQL view, don't use/create tablediff --git a/manager/shared/src/main/java/org/openremote/manager/shared/security/User.java b/manager/shared/src/main/java/org/openremote/manager/shared/security/User.javaindex c6faede7f..dec423426 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/security/User.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/security/User.java@@ -26,19 +26,18 @@ import org.hibernate.validator.constraints.Email;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.Id;-import javax.persistence.Transient;import javax.validation.constraints.NotNull;import javax.validation.constraints.Pattern;import javax.validation.constraints.Size;/**- * This can be used (among other things) to query the Keycloak USER_ENTITY table in JPA queries.+ * This can be used (among other things) to query the USER_ENTITY table in JPA queries.*/@Entity@Subselect("select * from USER_ENTITY") // Map this immutable to an SQL view, don't use/create tablepublic class User {- @Formula("(select r.NAME from REALM r where r.ID = REALM_ID")+ @Formula("(select r.NAME from REALM r where r.ID = REALM_ID)")protected String realm;@Column(name = "REALM_ID")diff --git a/manager/test/src/main/groovy/org/openremote/test/ClientSecurityService.java b/manager/test/src/main/groovy/org/openremote/test/ClientSecurityService.javaindex 0ce6edf25..68e44ae8b 100644--- a/manager/test/src/main/groovy/org/openremote/test/ClientSecurityService.java+++ b/manager/test/src/main/groovy/org/openremote/test/ClientSecurityService.java@@ -24,13 +24,10 @@ import org.keycloak.adapters.KeycloakDeployment;import org.keycloak.adapters.rotation.AdapterRSATokenVerifier;import org.keycloak.representations.AccessToken;import org.openremote.manager.client.interop.keycloak.AuthToken;-import org.openremote.manager.client.interop.keycloak.LoginOptions;-import org.openremote.manager.client.interop.keycloak.LogoutOptions;import org.openremote.manager.client.service.SecurityService;+import org.openremote.manager.shared.http.RequestParams;import org.openremote.model.Constants;-import java.util.function.Consumer;-/*** Does the same job as keycloak.js implementation.*/@@ -57,13 +54,13 @@ public class ClientSecurityService implements SecurityService {}@Override- public void login() {- throw new UnsupportedOperationException();+ public String getUsername() {+ return getParsedToken().getPreferredUsername();}@Override- public void login(LoginOptions options) {- throw new UnsupportedOperationException();+ public String getFullName() {+ return getParsedToken().getName();}@Override@@ -71,21 +68,6 @@ public class ClientSecurityService implements SecurityService {throw new UnsupportedOperationException();}- @Override- public void logout(LogoutOptions options) {- throw new UnsupportedOperationException();- }-- @Override- public void register() {- throw new UnsupportedOperationException();- }-- @Override- public void register(LoginOptions options) {- throw new UnsupportedOperationException();- }-@Overridepublic boolean isSuperUser() {return keycloakDeployment.getRealm().equals(Constants.MASTER_REALM) && hasRealmRole(Constants.REALM_ADMIN_ROLE);@@ -110,59 +92,29 @@ public class ClientSecurityService implements SecurityService {}@Override- public boolean isTokenExpired() {- updateAccessToken();- return false;- }-- @Override- public boolean isTokenExpired(int minValiditySeconds) {- throw new UnsupportedOperationException();- }-- @Override- public void clearToken() {- throw new UnsupportedOperationException();- }-- @Override- public void onTokenExpired(Runnable expiredFn) {- throw new UnsupportedOperationException();- }-- @Override- public void onAuthSuccess(Runnable expiredFn) {- throw new UnsupportedOperationException();- }-- @Override- public void onAuthLogout(Runnable expiredFn) {- throw new UnsupportedOperationException();- }-- @Override- public void updateToken(Consumer<Boolean> successFn, Runnable errorFn) {- successFn.accept(true);+ public String getAuthenticatedRealm() {+ return keycloakDeployment.getRealm();}@Override- public void updateToken(int minValiditySeconds, Consumer<Boolean> successFn, Runnable errorFn) {- successFn.accept(true);+ public <OUT> void setCredentials(RequestParams<OUT> requestParams) {+ requestParams.withBearerAuth(getToken());}@Override- public String getAuthenticatedRealm() {- return keycloakDeployment.getRealm();+ public String setCredentials(String serviceUrl) {+ String authenticatedServiceUrl = serviceUrl+ + "?Auth-Realm=" + getAuthenticatedRealm()+ + "&Authorization=Bearer " + getToken();+ return authenticatedServiceUrl;}- @Override- public String getToken() {+ protected String getToken() {updateAccessToken();return token;}- @Override- public AuthToken getParsedToken() {+ protected AuthToken getParsedToken() {updateAccessToken();return new AuthToken() {@Override@@ -177,8 +129,4 @@ public class ClientSecurityService implements SecurityService {};}- @Override- public String getRefreshToken() {- throw new UnsupportedOperationException();- }}diff --git a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovyindex 4f1c2b79e..c90b3e408 100644--- a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy+++ b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy@@ -7,21 +7,20 @@ import org.openremote.container.Containerimport org.openremote.container.ContainerServiceimport org.openremote.container.message.MessageBrokerServiceimport org.openremote.container.message.MessageBrokerSetupService-import org.openremote.container.persistence.PersistenceService-import org.openremote.container.security.IdentityServiceimport org.openremote.container.security.keycloak.KeycloakIdentityProviderimport org.openremote.container.timer.TimerServiceimport org.openremote.manager.server.agent.AgentServiceimport org.openremote.manager.server.apps.ConsoleAppService+import org.openremote.manager.server.asset.AssetAttributeLinkingServiceimport org.openremote.manager.server.asset.AssetProcessingServiceimport org.openremote.manager.server.asset.AssetStorageService-import org.openremote.manager.server.asset.AssetAttributeLinkingServiceimport org.openremote.manager.server.concurrent.ManagerExecutorServiceimport org.openremote.manager.server.datapoint.AssetDatapointServiceimport org.openremote.manager.server.event.ClientEventServiceimport org.openremote.manager.server.i18n.I18NServiceimport org.openremote.manager.server.map.MapServiceimport org.openremote.manager.server.notification.NotificationService+import org.openremote.manager.server.persistence.ManagerPersistenceServiceimport org.openremote.manager.server.rules.RulesEngineimport org.openremote.manager.server.rules.RulesServiceimport org.openremote.manager.server.rules.RulesetStorageService@@ -56,7 +55,7 @@ trait ManagerContainerTrait extends ContainerTrait {new TimerService(),new ManagerExecutorService(),new I18NService(),- new PersistenceService(),+ new ManagerPersistenceService(),new MessageBrokerSetupService(),new ManagerIdentityService(),new SetupService(),diff --git a/platform/rpi3/README.md b/platform/rpi3/README.mdindex e34fb480e..6e383df4b 100644--- a/platform/rpi3/README.md+++ b/platform/rpi3/README.md@@ -41,8 +41,6 @@ By default a dummy CA and self-signed certificates are generated for the Docker## Deploying OpenRemote containers-TODO: This doesn't work yet, still have to write a replacement for Keycloak identity service!-The Docker images for OpenRemote can be build on your x86 workstation with the QEMU emulator for the ARM environment. After building the images, you can export and load them onto the Raspberry Pi.First build the base image:@@ -60,6 +58,8 @@ docker build -t openremote/rpi-postgresql:latest -f postgresql/rpi3.Dockerfile pdocker build -t openremote/rpi-manager:latest -f manager/build/install/rpi3.Dockerfile manager/build/install```+TODO: The Manager image uses Oracle JDK by default, which must be licensed if deployed in production! You can switch to the much slower OpenJDK in the `Dockerfile`. We expect a faster OpenJDK to be available with AARCH64 OS.+Copy them to your Raspberry Pi (replace `openremote1` with your `DOCKER_MACHINE_NAME`):```@@ -72,4 +72,6 @@ Deploy the containers, providing the IP/hostname of your Raspberry Pi:```IDENTITY_NETWORK_HOST=10.0.0.123 docker-compose -p openremote -f profile/demo_rpi.yml up-```\ No newline at end of file+```++Open the Manager UI on `https://10.0.0.123`, accepting the self-signed demo SSL certificate. Login with `admin` and password `secret`. Edit the profile to change the admin password and other settings.diff --git a/profile/demo_rpi.yml b/profile/demo_rpi.ymlindex b42660878..5aa3cc49a 100644--- a/profile/demo_rpi.yml+++ b/profile/demo_rpi.yml@@ -1,8 +1,6 @@# Demo setup of OpenRemote v3 on Rasperry Pi 3#-# TODO Not finished, doesn't work-#-version: '2'+version: '2.1'services:# The frontend proxy, terminates SSL/TLS connections and forwards them to the Manager backend.@@ -46,22 +44,26 @@ services:TZ: Europe/Zurich# If developer mode is enabled, all setup tasks will be executed on application startup.- # This will clean all data in Keycloak and the Manager database, and then import demo/test+ # This will clean all data in the Manager database, and then import demo/test# data. Some caching and other runtime performance-optimizations will also be disabled.DEV_MODE: 'false'# If you are not running in developer mode, and this is the first time you are starting# the application, you can configure which setup tasks you want to execute. Careful,- # these tasks will clean and populate Keycloak and the Manager database with demo data!+ # these tasks will clean and populate the Manager database with demo data!SETUP_INIT_CLEAN_DATABASE: 'true'- SETUP_KEYCLOAK_ADMIN_PASSWORD: secret+ SETUP_BASIC_IDENTITY_ADMIN_PASSWORD: secretSETUP_IMPORT_DEMO_USERS: 'true'SETUP_IMPORT_DEMO_ASSETS: 'true'SETUP_IMPORT_DEMO_RULES: 'true'- # The public host name of this OpenRemote installation. This name is used in bearer tokens- # and must be the name you access the web services under.- IDENTITY_NETWORK_HOST: localhost+ # Use basic identity service instead of Keycloak, set master admin password+ MANAGER_IDENTITY_PROVIDER: basic+ SETUP_BASIC_IDENTITY_ADMIN_PASSWORD: 'secret'++ # The public host name of this OpenRemote installation. This name must be the name you+ # access the web services under.+ IDENTITY_NETWORK_HOST: ${IDENTITY_NETWORK_HOST:-10.0.0.123}# Set if SSL is enabled on the frontend reverse proxy and all internal proxies should assume httpsIDENTITY_NETWORK_SECURE: 'true'@@ -93,8 +95,6 @@ services:# This service needs access to other services on the Docker network.links:- postgresql-# TODO Replace keycloak service-# - keycloak# Configure logging of the container, see config/logging.propertieslogging: