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
Remove basic identity provider (#3051)
Koen9e31a4dd284d
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.javadeleted file mode 100644index f8fbce3df..000000000--- a/container/src/main/java/org/openremote/container/security/basic/BasicAuthContext.java+++ /dev/null@@ -1,71 +0,0 @@-/*- * Copyright 2017, OpenRemote Inc.- *- * 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 <https://www.gnu.org/licenses/>.- *- * SPDX-License-Identifier: AGPL-3.0-or-later- */-package org.openremote.container.security.basic;--import java.security.Principal;-import org.openremote.container.security.AuthContext;--/** 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 getAuthenticatedRealmName() {- return authenticatedRealm;- }-- @Override- public String getUsername() {- return username;- }-- @Override- public String getUserId() {- return userId;- }-- @Override- public String getClientId() {- return null;- }-- @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.javadeleted file mode 100644index 9c251aa3d..000000000--- a/container/src/main/java/org/openremote/container/security/basic/BasicIdentityProvider.java+++ /dev/null@@ -1,121 +0,0 @@-/*- * Copyright 2017, OpenRemote Inc.- *- * 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 <https://www.gnu.org/licenses/>.- *- * SPDX-License-Identifier: AGPL-3.0-or-later- */-package org.openremote.container.security.basic;--import io.undertow.security.idm.Account;-import jakarta.persistence.NoResultException;-import jakarta.persistence.NonUniqueResultException;-import jakarta.security.enterprise.AuthenticationException;-import jakarta.servlet.FilterRegistration;-import jakarta.servlet.ServletContext;-import java.security.Principal;-import java.util.Set;-import java.util.concurrent.CompletableFuture;-import java.util.logging.Logger;-import org.openremote.container.persistence.PersistenceService;-import org.openremote.container.security.IdentityProvider;-import org.openremote.container.security.OIDCTokenResponse;-import org.openremote.container.security.TokenPrincipal;-import org.openremote.model.Constants;-import org.openremote.model.Container;--@Deprecated-/** This identity provider is scheduled to be removed */-public abstract class BasicIdentityProvider implements IdentityProvider {-- private static final Logger LOG = Logger.getLogger(BasicIdentityProvider.class.getName());- protected PersistenceService persistenceService;-- @Override- public void init(Container container) {- this.persistenceService = container.getService(PersistenceService.class);- // Add schema and scripts for the PUBLIC realm to replicate keycloak user tables- this.persistenceService- .getDefaultSchemaLocations()- .add("classpath:org/openremote/container/persistence/schema/basicidentityprovider");- this.persistenceService.getSchemas().add("public");- }-- @Override- public void start(Container container) {}-- @Override- public void stop(Container container) {}-- @Override- public FilterRegistration.Dynamic secureDeployment(ServletContext servletContext) {- throw new UnsupportedOperationException(- "Basic authentication is not supported for servlet deployments");- }-- 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 PUBLIC.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 getDefaultRoles();- }- };- }-- protected abstract Set<String> getDefaultRoles();-- @Override- public TokenPrincipal verify(String realm, String accessToken) throws AuthenticationException {- return null;- }-- @Override- public CompletableFuture<OIDCTokenResponse> authenticate(- String realm, String clientId, String clientSecret) {- return CompletableFuture.failedFuture(- new AuthenticationException("This provider does not support bearer tokens"));- }-}diff --git a/container/src/main/java/org/openremote/container/security/basic/PasswordStorage.java b/container/src/main/java/org/openremote/container/security/basic/PasswordStorage.javadeleted file mode 100644index 89ba790f7..000000000--- a/container/src/main/java/org/openremote/container/security/basic/PasswordStorage.java+++ /dev/null@@ -1,225 +0,0 @@-/**- * 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 javax.crypto.SecretKeyFactory;-import javax.crypto.spec.PBEKeySpec;-import java.security.NoSuchAlgorithmException;-import java.security.SecureRandom;-import java.security.spec.InvalidKeySpecException;-import java.util.Base64;-import java.util.logging.Logger;--/**- * https://github.com/defuse/password-hashing- */-public class PasswordStorage {-- private static final Logger LOG = Logger.getLogger(PasswordStorage.class.getName());-- @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 = 1000;-- // 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 {- LOG.fine("Cache miss, hashing password...") ;- PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, 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- );- }- }-- private static byte[] fromBase64(String hex) {- return Base64.getDecoder().decode(hex);- }-- private static String toBase64(byte[] array) {- return Base64.getEncoder().encodeToString(array);- }--}diff --git a/container/src/main/java/org/openremote/container/web/WebResource.java b/container/src/main/java/org/openremote/container/web/WebResource.javaindex 8bc0fa208..ef4973f67 100644--- a/container/src/main/java/org/openremote/container/web/WebResource.java+++ b/container/src/main/java/org/openremote/container/web/WebResource.java@@ -28,7 +28,6 @@ import jakarta.ws.rs.core.*;import java.security.Principal;import org.openremote.container.security.AuthContext;import org.openremote.container.security.TokenPrincipal;-import org.openremote.container.security.basic.BasicAuthContext;public class WebResource implements AuthContext {@@ -62,7 +61,6 @@ public class WebResource implements AuthContext {return switch (principal) {case null -> null;case TokenPrincipal tokenPrincipal -> tokenPrincipal;- case BasicAuthContext basicAuthContext -> basicAuthContext;default ->throw new WebApplicationException("Unsupported user principal type: " + principal, INTERNAL_SERVER_ERROR);diff --git a/container/src/main/resources/org/openremote/container/persistence/schema/basicidentityprovider/V20191202_00__BasicIdentityProvider.sql b/container/src/main/resources/org/openremote/container/persistence/schema/basicidentityprovider/V20191202_00__BasicIdentityProvider.sqldeleted file mode 100644index 47fc83670..000000000--- a/container/src/main/resources/org/openremote/container/persistence/schema/basicidentityprovider/V20191202_00__BasicIdentityProvider.sql+++ /dev/null@@ -1,45 +0,0 @@-create table PUBLIC.REALM (- ID varchar(36) not null primary key,- NAME varchar(255) unique not null,- ENABLED boolean default false not null,- RESET_PASSWORD_ALLOWED boolean default true not null,- DUPLICATE_EMAILS_ALLOWED boolean default false not null,- REMEMBER_ME boolean default false not null,- REGISTRATION_ALLOWED boolean default false not null,- REG_EMAIL_AS_USERNAME boolean default false not null,- VERIFY_EMAIL boolean default false not null,- LOGIN_WITH_EMAIL_ALLOWED boolean default false not null,- LOGIN_THEME varchar(255) default null,- ACCOUNT_THEME varchar(255) default null,- ADMIN_THEME varchar(255) default null,- EMAIL_THEME varchar(255) default null,- ACCESS_TOKEN_LIFESPAN integer default null,- NOT_BEFORE integer-);--create table PUBLIC.KEYCLOAK_ROLE (- ID varchar(36) not null primary key,- REALM_ID varchar(36) not null references PUBLIC.REALM,- CLIENT varchar(255) default null,- NAME varchar(255) not null,- DESCRIPTION varchar(255) default null-);--create table PUBLIC.REALM_ATTRIBUTE (- NAME varchar(255) not null,- VALUE varchar(255),- REALM_ID varchar(36) not null references PUBLIC.REALM,- primary key (NAME, REALM_ID)-);--create table PUBLIC.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/kubernetes/manager/values.yaml b/kubernetes/manager/values.yamlindex 5723b7f80..ac19a54ad 100644--- a/kubernetes/manager/values.yaml+++ b/kubernetes/manager/values.yaml@@ -210,8 +210,6 @@ or:# The identity provider implementation to use for managing user identities, roles, and# access authorization. The default is 'keycloak' which requires a separate service but# provides full multi-tenancy identity, role permissions, and user session timeouts.- # The 'basic' provider supports only superusers and their text passwords, managed in a- # simple database table, and always requires a new login when a page is reloaded.identityProvider: "keycloak"# For the Keycloak identity provider, you may configure session timeouts of frontend apps. Thisdiff --git a/manager/src/main/java/org/openremote/manager/security/ManagerBasicIdentityProvider.java b/manager/src/main/java/org/openremote/manager/security/ManagerBasicIdentityProvider.javadeleted file mode 100644index b59aa596a..000000000--- a/manager/src/main/java/org/openremote/manager/security/ManagerBasicIdentityProvider.java+++ /dev/null@@ -1,284 +0,0 @@-/*- * Copyright 2017, OpenRemote Inc.- *- * 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 <https://www.gnu.org/licenses/>.- *- * SPDX-License-Identifier: AGPL-3.0-or-later- */-package org.openremote.manager.security;--import static org.openremote.model.Constants.*;--import jakarta.security.enterprise.AuthenticationException;-import java.sql.PreparedStatement;-import java.util.Objects;-import java.util.Set;-import java.util.UUID;-import java.util.logging.Logger;-import org.hibernate.Session;-import org.openremote.container.security.AuthContext;-import org.openremote.container.security.TokenPrincipal;-import org.openremote.container.security.basic.BasicIdentityProvider;-import org.openremote.container.security.basic.PasswordStorage;-import org.openremote.model.Container;-import org.openremote.model.query.UserQuery;-import org.openremote.model.security.*;-import org.openremote.model.util.TextUtil;--public class ManagerBasicIdentityProvider extends BasicIdentityProvider- implements ManagerIdentityProvider {-- private static final Logger LOG = Logger.getLogger(ManagerBasicIdentityProvider.class.getName());- protected ManagerIdentityService identityService;- protected String adminPassword;-- @Override- public void init(Container container) {- super.init(container);- this.identityService = container.getService(ManagerIdentityService.class);- adminPassword =- container.getConfig().getOrDefault(OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT);- }-- @Override- public void start(Container container) {- super.start(container);-- // Create master realm and admin user- if (!realmExists(MASTER_REALM)) {- LOG.info("Creating master realm and admin user");-- // Configure the master realm- persistenceService.doTransaction(- em ->- em.unwrap(Session.class)- .doWork(- connection -> {- String sql =- "insert into PUBLIC.REALM(ID, NAME, ENABLED) values ('master', 'master', true)";- PreparedStatement st = connection.prepareStatement(sql);- st.executeUpdate();- st.close();-- sql =- "insert into PUBLIC.REALM_ATTRIBUTE(REALM_ID, NAME, VALUE) values ('master', 'displayName', 'Master')";- st = connection.prepareStatement(sql);- st.executeUpdate();- st.close();- }));-- User adminUser = new User();- adminUser.setUsername(MASTER_REALM_ADMIN_USER);- createUpdateUser(MASTER_REALM, adminUser, adminPassword, true);- }- }-- @Override- protected Set<String> getDefaultRoles() {- return ClientRole.ALL_ROLES;- }-- @Override- public User[] queryUsers(UserQuery userQuery) {- return ManagerIdentityProvider.getUsersFromDb(persistenceService, userQuery);- }-- @Override- public User getUser(String userId) {- return ManagerIdentityProvider.getUserByIdFromDb(persistenceService, userId);- }-- @Override- public User getUserByUsername(String realm, String username) {- return ManagerIdentityProvider.getUserByUsernameFromDb(persistenceService, realm, username);- }-- @Override- public User createUpdateUser(String realm, User user, String password, boolean allowUpdate) {- if (!realm.equals(MASTER_REALM)) {- throw new UnsupportedOperationException(- "This provider does not support realms other than master");- }-- if (TextUtil.isNullOrEmpty(password)) {- throw new IllegalStateException("Password must be specified for basic identity provider");- }-- LOG.info("Creating user: " + user);- user.setId(UUID.randomUUID().toString());- persistenceService.doTransaction(- em ->- em.unwrap(Session.class)- .doWork(- connection -> {- String sql =- "insert into PUBLIC.USER_ENTITY(ID, REALM_ID, USERNAME, PASSWORD, FIRST_NAME, LAST_NAME, EMAIL, ENABLED) values (?, ?, ?, ?, ?, ?, ?, ?)";- if (allowUpdate) {- sql += " ON CONFLICT (ID, USERNAME) DO UPDATE";- }- sql +=- " SET username = excluded.username, password = excluded.password, first_name = excluded.first_name, last_name = excluded.last_name, email = excluded.email, enabled = excluded.enabled";- try (PreparedStatement st = connection.prepareStatement(sql)) {- st.setString(1, UUID.randomUUID().toString());- st.setString(2, MASTER_REALM); // For master REALM NAME and ID are the same- st.setString(3, user.getUsername());- st.setString(4, PasswordStorage.createHash(password));- st.setString(5, user.getFirstName());- st.setString(6, user.getLastName());- st.setString(7, user.getEmail());- st.setBoolean(8, user.getEnabled() != null ? user.getEnabled() : true);- st.executeUpdate();- }- }));- return user;- }-- @Override- public void deleteUser(String realm, String userId) {- LOG.info("Deleting user: " + userId);- persistenceService.doTransaction(- em -> {- User user = em.find(User.class, userId);- if (user != null) {- em.remove(user);- } else {- LOG.info("Cannot delete user as ID not found: " + userId);- }- });- }-- @Override- public void requestPasswordReset(String realm, String userId) {- throw new UnsupportedOperationException("This provider does not support password reset");- }-- @Override- public void resetPassword(String realm, String userId, Credential credential) {- throw new UnsupportedOperationException("This provider does not support password reset");- }-- @Override- public String resetSecret(String realm, String userId, String secret) {- throw new UnsupportedOperationException("This provider does not support secret reset");- }-- @Override- public Role[] getClientRoles(String realm, String client) {- if (client != null && !MASTER_REALM.equals(client)) {- throw new IllegalStateException("This provider only has a single master realm");- }- return ClientRole.ALL_ROLES.stream()- .map(role -> new Role(UUID.randomUUID().toString(), role, false, true, null))- .toArray(Role[]::new);- }-- @Override- public void updateClientRoles(String realm, String client, Role[] roles) {- throw new UnsupportedOperationException("This provider does not support updating roles");- }-- @Override- public String[] getUserClientRoles(String realm, String userId, String client) {- if (KEYCLOAK_CLIENT_ID.equals(client)) {- return ClientRole.ALL_ROLES.toArray(new String[0]);- }- return new String[0];- }-- @Override- public String[] getUserRealmRoles(String realm, String userId) {- throw new UnsupportedOperationException("This provider does not support user realm roles");- }-- @Override- public void updateUserClientRoles(String realm, String userId, String client, String... roles) {- throw new UnsupportedOperationException("This provider does not support updating user roles");- }-- @Override- public void updateUserRealmRoles(String realm, String userId, String... roles) {- throw new UnsupportedOperationException(- "This provider does not support updating user realm roles");- }-- @Override- public boolean isMasterRealmAdmin(String userId) {- return true;- }-- @Override- public boolean isRestrictedUser(AuthContext authContext) {- return false;- }-- @Override- public boolean isUserInRealm(String userId, String realm) {- return ManagerIdentityProvider.userInRealmFromDb(persistenceService, userId, realm);- }-- @Override- public Realm[] getRealms() {- return ManagerIdentityProvider.getRealmsFromDb(persistenceService);- }-- @Override- public Realm getRealm(String realm) {- return ManagerIdentityProvider.getRealmFromDb(persistenceService, realm);- }-- @Override- public void updateRealm(Realm realm) {- throw new UnsupportedOperationException("This provider does not support modifying realms");- }-- @Override- public Realm createRealm(Realm realm) {- throw new UnsupportedOperationException("This provider does not support multiple realms");- }-- @Override- public void deleteRealm(String realm) {- throw new UnsupportedOperationException("This provider does not support multiple realms");- }-- @Override- public boolean isRealmActiveAndAccessible(AuthContext authContext, Realm realm) {- return Objects.equals(realm.getId(), MASTER_REALM);- }-- @Override- public boolean isRealmActiveAndAccessible(AuthContext authContext, String realm) {- return Objects.equals(realm, MASTER_REALM);- }-- @Override- public boolean realmExists(String realm) {- return ManagerIdentityProvider.realmExistsFromDb(persistenceService, realm);- }-- @Override- public String getFrontendURI() {- return null;- }-- @Override- public String toString() {- return getClass().getSimpleName() + "{}";- }-- @Override- public TokenPrincipal verify(String realm, String accessToken) throws AuthenticationException {- return null;- }-}diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityService.java b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityService.javaindex 519977bdf..552c4d4da 100644--- a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityService.java+++ b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityService.java@@ -60,10 +60,6 @@ public class ManagerIdentityService extends IdentityService {LOG.info("Enabling Keycloak identity provider");this.identityProvider = new ManagerKeycloakIdentityProvider();}- case "basic" -> {- LOG.info("Enabling basic identity provider");- this.identityProvider = new ManagerBasicIdentityProvider();- }default ->throw new UnsupportedOperationException("Unknown identity provider: " + identityProviderType);diff --git a/model/src/main/java/org/openremote/model/manager/Auth.java b/model/src/main/java/org/openremote/model/manager/Auth.javaindex 0128394ee..5799fb39f 100644--- a/model/src/main/java/org/openremote/model/manager/Auth.java+++ b/model/src/main/java/org/openremote/model/manager/Auth.java@@ -20,6 +20,5 @@ package org.openremote.model.manager;public enum Auth {KEYCLOAK,- BASIC,NONE}diff --git a/model/src/main/java/org/openremote/model/manager/ManagerConfig.java b/model/src/main/java/org/openremote/model/manager/ManagerConfig.javaindex 5ba95a878..dc65979c8 100644--- a/model/src/main/java/org/openremote/model/manager/ManagerConfig.java+++ b/model/src/main/java/org/openremote/model/manager/ManagerConfig.java@@ -18,8 +18,6 @@*/package org.openremote.model.manager;-import org.openremote.model.auth.UsernamePassword;-public class ManagerConfig {protected String managerUrl;protected String keycloakUrl;@@ -33,12 +31,9 @@ public class ManagerConfig {protected String[] loadTranslations;protected boolean loadDescriptors;protected String translationsLoadPath;- protected boolean skipFallbackToBasicAuth;protected boolean applyConfigToAdmin;protected Auth auth;- protected UsernamePassword credentials;protected EventProviderType eventProviderType;protected Object configureTranslationsOptions;- protected Object basicLoginProvider;protected String defaultLanguage;}diff --git a/profile/basic-identity.yml b/profile/basic-identity.ymldeleted file mode 100644index ef99c48d3..000000000--- a/profile/basic-identity.yml+++ /dev/null@@ -1,43 +0,0 @@-# OpenRemote v3-#-# Profile that runs the vanilla stack on https://localhost using a self-signed SSL certificate,-# with username 'admin' and password 'secret' using the basic identity provider (i.e. no keycloak-# for constrained devices such as edge gateways). There is no map data available in the vanilla-# system so the map tile server will not function. Persistent data is stored in a docker-# volume called postgresql-data between restarts, simply delete this volume to reset the-# system to an empty state.-#-# Please see deploy.yml for configuration details for each service.-#-volumes:- manager-data:- postgresql-data:--services:- proxy:- extends:- file: deploy.yml- service: proxy- depends_on:- manager:- condition: service_healthy-- postgresql:- extends:- file: deploy.yml- service: postgresql- volumes:- - postgresql-data:/var/lib/postgresql/data- - manager-data:/storage-- manager:- extends:- file: deploy.yml- service: manager- depends_on:- postgresql:- condition: service_healthy- volumes:- - manager-data:/storage- environment:- OR_IDENTITY_PROVIDER: basicdiff --git a/profile/deploy.yml b/profile/deploy.ymlindex bef6fe445..ce188ac1e 100644--- a/profile/deploy.yml+++ b/profile/deploy.yml@@ -312,8 +312,6 @@ services:# The identity provider implementation to use for managing user identities, roles, and# access authorization. The default is 'keycloak' which requires a separate service but# provides full multi-tenancy identity, role permissions, and user session timeouts.- # The 'basic' provider supports only superusers and their text passwords, managed in a- # simple database table, and always requires a new login when a page is reloaded.OR_IDENTITY_PROVIDER: ${OR_IDENTITY_PROVIDER:-keycloak}# For the Keycloak identity provider, you may configure session timeouts of frontend apps. Thisdiff --git a/ui/component/core/src/index.ts b/ui/component/core/src/index.tsindex 8592b7045..a6e5cd59c 100644--- a/ui/component/core/src/index.ts+++ b/ui/component/core/src/index.ts@@ -24,15 +24,7 @@ import { type EventProvider, type EventProviderFactory, EventProviderStatus, Webimport i18next, { type InitOptions } from "i18next";import i18nextBackend from "i18next-http-backend";import moment from "moment";-import {- AssetModelUtil,- Auth,- type ConsoleAppConfig,- EventProviderType,- type ManagerConfig,- type User,- type UsernamePassword,-} from "@openremote/model";+import { AssetModelUtil, Auth, type ConsoleAppConfig, EventProviderType, type ManagerConfig } from "@openremote/model";import * as Util from "./util";import { createMdiIconSet, createSvgIconSet, IconSets, OrIconSet } from "@openremote/or-icon";import Keycloak from "keycloak-js";@@ -84,13 +76,6 @@ export enum OREvent {export interface LoginOptions {redirectUrl?: string;action?: string;- credentials?: UsernamePassword;-}--export interface BasicLoginResult {- username: string;- password: string;- cancel: boolean;}export interface Languages {@@ -221,8 +206,6 @@ export class Manager implements EventProviderFactory {});}}- } else if (this._basicIdentity && this._basicIdentity.roles) {- roleMap.set(this._config.clientId!, this._basicIdentity.roles!);}return roleMap;@@ -308,16 +291,9 @@ export class Manager implements EventProviderFactory {private _config!: ManagerConfig;private _authenticated: boolean = false;private _ready: boolean = false;- private _readyCallback?: () => PromiseLike<any>;private _name: string = "";private _username: string = "";private _keycloak?: Keycloak;- private _basicIdentity?: {- token: string | undefined;- user: User | undefined;- roles: string[] | undefined;- };-private _keycloakUpdateTokenInterval?: number = undefined;private _managerVersion: string = "";public _authServerUrl: string = "";@@ -372,11 +348,7 @@ export class Manager implements EventProviderFactory {});this._console = orConsole;- if (this._config.auth === Auth.BASIC) {- // BASIC auth will likely require UI so lets init translation at least- success = (await this.doTranslateInit()) && success;- success = await this.doAuthInit();- } else if (this._config.auth === Auth.KEYCLOAK) {+ if (this._config.auth === Auth.KEYCLOAK) {// The info endpoint of the manager might return a relative URL (relative to the manager)if (!this._config.keycloakUrl && this._authServerUrl) {const managerURL = new URL(this._config.managerUrl!);@@ -417,14 +389,6 @@ export class Manager implements EventProviderFactory {this._config.keycloakUrl = this._config.keycloakUrl.replace(/\/+$/, "");success = await this.doAuthInit();-- // If failed then we can assume keycloak auth requested but unavailable- if (!success && !this._config.skipFallbackToBasicAuth) {- // Try fallback to BASIC- console.debug("Falling back to basic auth");- this._config.auth = Auth.BASIC;- success = await this.doAuthInit();- }}if (!success) {@@ -455,9 +419,6 @@ export class Manager implements EventProviderFactory {if (success) {success = await this.doEventsSubscriptionInit();- if (this._readyCallback) {- await this._readyCallback();- }this._ready = true;this._emitEvent(OREvent.READY);} else {@@ -583,9 +544,6 @@ export class Manager implements EventProviderFactory {protected async doAuthInit(): Promise<boolean> {let success = true;switch (this._config.auth) {- case Auth.BASIC:- success = await this.initialiseBasicAuth();- break;case Auth.KEYCLOAK:success = await this.loadAndInitialiseKeycloak();break;@@ -751,24 +709,11 @@ export class Manager implements EventProviderFactory {this._keycloakUpdateTokenInterval = undefined;}this._keycloak.logout(redirectUrl && redirectUrl !== "" ? { redirectUri: redirectUrl } : undefined);- } else if (this._basicIdentity) {- this._basicIdentity = undefined;- if (redirectUrl) {- window.location.href = redirectUrl;- } else {- window.location.reload();- }}}public login(options?: LoginOptions) {switch (this._config.auth) {- case Auth.BASIC:- if (options && options.credentials) {- this._config.credentials = Object.assign({}, options.credentials);- }- this.doBasicLogin();- break;case Auth.KEYCLOAK:if (this._keycloak) {const keycloakOptions: any = {};@@ -789,92 +734,6 @@ export class Manager implements EventProviderFactory {}}- protected async initialiseBasicAuth(): Promise<boolean> {- if (!this.config.basicLoginProvider) {- console.debug("No basicLoginProvider defined on config so cannot display login UI");- return false;- }-- if (this.config.autoLogin) {- // Delay basic login until other inits are done- this._readyCallback = () => {- return this.doBasicLogin();- };- }-- return true;- }-- protected async doBasicLogin() {- if (!this.config.basicLoginProvider) {- return;- }-- let result: BasicLoginResult = {- username: this.config.credentials?.username ? this.config.credentials?.username : "",- password: this.config.credentials?.password ? this.config.credentials?.password : "",- cancel: false,- };- let authenticated = false;-- this._basicIdentity = {- roles: undefined,- token: undefined,- user: undefined,- };-- while (!authenticated) {- result = await this.config.basicLoginProvider(result.username, result.password);-- if (result.cancel) {- console.debug("Basic authentication cancelled by user");- break;- }-- if (!result.username || !result.password) {- continue;- }-- // Update basic token so we can use rest api to make calls- this._basicIdentity!.token = btoa(result.username + ":" + result.password);- let success = false;-- try {- const userResponse = await rest.api.UserResource.getCurrent();- if (userResponse.status === 200) {- success = true;- this._basicIdentity!.user = userResponse.data;- }-- if (!success) {- // Undertow incorrectly returns 403 when no authorization header and a 401 when it is set and not valid- if (userResponse.status === 401 || userResponse.status === 403) {- console.debug("Basic authentication invalid credentials, trying again");- }- }- } catch (e) {- console.error("Basic auth failed: ", e);- }-- if (success) {- console.debug("Basic authentication successful");- authenticated = true;-- // Get user roles- const rolesResponse = await rest.api.UserResource.getCurrentUserClientRoles(this.clientId);- this._basicIdentity!.roles = rolesResponse.data;- } else {- console.debug("Unknown response so aborting");- this._basicIdentity = undefined;- break;- }- }-- if (authenticated) {- this._onAuthenticated();- }- }-public isSuperUser(): boolean {return !!(this.getRealm() && this.getRealm() === "master" && this.hasRealmRole("admin"));}@@ -907,10 +766,6 @@ export class Manager implements EventProviderFactory {if (this.getKeycloakToken()) {return "Bearer " + this.getKeycloakToken();}-- if (this.getBasicToken()) {- return "Basic " + this.getBasicToken();- }}/**@@ -921,8 +776,6 @@ export class Manager implements EventProviderFactory {const keycloakToken = await this.retrieveKeycloakToken();if (keycloakToken) {return "Bearer " + keycloakToken;- } else {- return "Basic " + this.getBasicToken();}}@@ -945,10 +798,6 @@ export class Manager implements EventProviderFactory {return undefined;}- public getBasicToken(): string | undefined {- return this._basicIdentity ? this._basicIdentity.token : undefined;- }-public getRealm(): string | undefined {if (this._config) {return this._config.realm;diff --git a/ui/component/or-app/src/index.ts b/ui/component/or-app/src/index.tsindex ee8255065..d07496e19 100644--- a/ui/component/or-app/src/index.ts+++ b/ui/component/or-app/src/index.ts@@ -26,23 +26,20 @@ import "@openremote/or-icon";import { updateMetadata } from "pwa-helpers/metadata";import { i18next } from "@openremote/or-translate";import manager, {- type BasicLoginResult,DefaultColor2,DefaultColor3,DefaultColor4,type Manager,normaliseConfig,- ORError,OREvent,Util,} from "@openremote/core";import { DEFAULT_LANGUAGES, HeaderConfig } from "./or-header";-import { OrMwcDialog, showDialog } from "@openremote/or-mwc-components/or-mwc-dialog";+import { OrMwcDialog } from "@openremote/or-mwc-components/or-mwc-dialog";import { showErrorDialog } from "@openremote/or-vaadin-components/or-vaadin-confirm-dialog";import { OrMwcSnackbar, showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar";import { AnyAction, type Store, type Unsubscribe } from "@reduxjs/toolkit";import { type AppStateKeyed, setOffline, setVisibility, updatePage, updateRealm } from "./app";-import { InputType, type OrInputChangedEvent } from "@openremote/or-mwc-components/or-mwc-input";import {dialogFooterRenderer,dialogHeaderRenderer,@@ -245,24 +242,9 @@ export class OrApp<S extends AppStateKeyed> extends LitElement {if (!managerConfig.defaultLanguage) {managerConfig.defaultLanguage = Util.getBrowserLanguage();}- managerConfig.skipFallbackToBasicAuth = true; // We do this so we can load styling config before displaying basic login- managerConfig.basicLoginProvider = (u: any, p: any) => this.doBasicLogin(u, p);-console.info("Initialising the manager");manager.init(managerConfig).then(async (success) => {- if (- !success &&- manager.error === ORError.AUTH_FAILED &&- (!managerConfig.auth || managerConfig.auth === Auth.KEYCLOAK)- ) {- this.doAppConfigInit();-- // Fallback to basic auth now styling is loaded- managerConfig.auth = Auth.BASIC;- success = await manager.init(managerConfig);- }-if (success) {this.doAppConfigInit();@@ -650,71 +632,6 @@ export class OrApp<S extends AppStateKeyed> extends LitElement {}}- protected doBasicLogin(username: string | undefined, password: string | undefined): PromiseLike<BasicLoginResult> {- const deferred = new Util.Deferred<BasicLoginResult>();-- let u = username;- let p = password;-- // language=CSS- const styles = html`- #login-logo { width: 24px; height: 24px; } #login_wrapper > or-mwc-input { margin: 10px 0; width: 100%; }- `;-- const dialog = showDialog(- new OrMwcDialog()- .setStyles(- html`<style>- ${styles}- </style>`- )- .setHeading(- html`<img id="login-logo" src="${this._config.logoMobile || this._config.logo}" /></or-icon><or-translate value="login"></or-translate>`- )- .setContent(html`- <div id="login_wrapper">- <or-mwc-input- label="${i18next.t("user")}"- .type="${InputType.TEXT}"- min="1"- required- .value="${username}"- @or-mwc-input-changed="${(e: OrInputChangedEvent) => (u = e.detail.value)}"- ></or-mwc-input>- <or-mwc-input- label="${i18next.t("password")}"- .type="${InputType.PASSWORD}"- min="1"- required- .value="${password}"- @or-mwc-input-changed="${(e: OrInputChangedEvent) => (p = e.detail.value)}"- ></or-mwc-input>- </div>- `)- .setActions([- {- actionName: "submit",- default: true,- action: () => {- deferred.resolve({- cancel: false,- username: u!,- password: p!,- });- },- content: html`<or-mwc-input- .type=${InputType.BUTTON}- label="${i18next.t("submit")}"- raised- ></or-mwc-input>`,- },- ]),- document.body- ); // Attach to document as or-app isn't visible until initialised-- return deferred.promise;- }-protected updateWindowTitle() {if (!this._initialised) {return;diff --git a/ui/test/playwright/index.js b/ui/test/playwright/index.jsindex 1afb389da..a6e9d59c8 100644--- a/ui/test/playwright/index.js+++ b/ui/test/playwright/index.js@@ -73,11 +73,10 @@ function subscribeAssetEvents(ids, requestCurrentValues, callback) {// TODO: consider rewriting this to use a mock `WebSocketEventProvider` so we can test @openremote/core and other componentsmanager.init = async () => {- manager._basicIdentity = {- // token: string | undefined,- // user: User | undefined,- roles: [ClientRole.WRITE_ASSETS, ClientRole.WRITE_ATTRIBUTES],- };+ // Shadow the prototype getter so `manager.hasRole` sees these roles without authenticating+ Object.defineProperty(manager, "roles", {+ get: () => new Map([["openremote", [ClientRole.WRITE_ASSETS, ClientRole.WRITE_ATTRIBUTES]]]),+ });manager._config = {clientId: "openremote",autoLogin: false,