Search in sources :

Example 96 with KeycloakSession

use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.

the class RolePolicyProviderFactory method updateRoles.

private void updateRoles(Policy policy, AuthorizationProvider authorization, Set<RolePolicyRepresentation.RoleDefinition> roles) {
    KeycloakSession session = authorization.getKeycloakSession();
    RealmModel realm = authorization.getRealm();
    Set<RolePolicyRepresentation.RoleDefinition> updatedRoles = new HashSet<>();
    if (roles != null) {
        for (RolePolicyRepresentation.RoleDefinition definition : roles) {
            String roleName = definition.getId();
            String clientId = null;
            int clientIdSeparator = roleName.indexOf("/");
            if (clientIdSeparator != -1) {
                clientId = roleName.substring(0, clientIdSeparator);
                roleName = roleName.substring(clientIdSeparator + 1);
            }
            RoleModel role;
            if (clientId == null) {
                role = realm.getRole(roleName);
                if (role == null) {
                    role = realm.getRoleById(roleName);
                }
            } else {
                ClientModel client = realm.getClientByClientId(clientId);
                if (client == null) {
                    throw new RuntimeException("Client with id [" + clientId + "] not found.");
                }
                role = client.getRole(roleName);
            }
            if (role == null) {
                throw new RuntimeException("Error while updating policy [" + policy.getName() + "]. Role [" + roleName + "] could not be found.");
            }
            definition.setId(role.getId());
            updatedRoles.add(definition);
        }
    }
    try {
        policy.putConfig("roles", JsonSerialization.writeValueAsString(updatedRoles));
    } catch (IOException cause) {
        throw new RuntimeException("Failed to serialize roles", cause);
    }
}
Also used : RolePolicyRepresentation(org.keycloak.representations.idm.authorization.RolePolicyRepresentation) RoleModel(org.keycloak.models.RoleModel) IOException(java.io.IOException) RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) KeycloakSession(org.keycloak.models.KeycloakSession) HashSet(java.util.HashSet)

Example 97 with KeycloakSession

use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.

the class LDAPStorageProviderFactory method createQuery.

/**
 *  !! This function must be called from try-with-resources block, otherwise Vault secrets may be leaked !!
 * @param sessionFactory
 * @param realmId
 * @param model
 * @return
 */
private LDAPQuery createQuery(KeycloakSessionFactory sessionFactory, final String realmId, final ComponentModel model) {
    class QueryHolder {

        LDAPQuery query;
    }
    final QueryHolder queryHolder = new QueryHolder();
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            session.getContext().setRealm(session.realms().getRealm(realmId));
            LDAPStorageProvider ldapFedProvider = (LDAPStorageProvider) session.getProvider(UserStorageProvider.class, model);
            RealmModel realm = session.realms().getRealm(realmId);
            queryHolder.query = LDAPUtils.createQueryForUserSearch(ldapFedProvider, realm);
        }
    });
    return queryHolder.query;
}
Also used : RealmModel(org.keycloak.models.RealmModel) LDAPQuery(org.keycloak.storage.ldap.idm.query.internal.LDAPQuery) KeycloakSessionTask(org.keycloak.models.KeycloakSessionTask) KeycloakSession(org.keycloak.models.KeycloakSession)

Example 98 with KeycloakSession

use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.

the class LDAPStorageProviderFactory method importLdapUsers.

protected SynchronizationResult importLdapUsers(KeycloakSessionFactory sessionFactory, final String realmId, final ComponentModel fedModel, List<LDAPObject> ldapUsers) {
    final SynchronizationResult syncResult = new SynchronizationResult();
    class BooleanHolder {

        private boolean value = true;
    }
    final BooleanHolder exists = new BooleanHolder();
    for (final LDAPObject ldapUser : ldapUsers) {
        try {
            // Process each user in it's own transaction to avoid global fail
            KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

                @Override
                public void run(KeycloakSession session) {
                    LDAPStorageProvider ldapFedProvider = (LDAPStorageProvider) session.getProvider(UserStorageProvider.class, fedModel);
                    RealmModel currentRealm = session.realms().getRealm(realmId);
                    session.getContext().setRealm(currentRealm);
                    String username = LDAPUtils.getUsername(ldapUser, ldapFedProvider.getLdapIdentityStore().getConfig());
                    exists.value = true;
                    LDAPUtils.checkUuid(ldapUser, ldapFedProvider.getLdapIdentityStore().getConfig());
                    UserModel currentUserLocal = session.userLocalStorage().getUserByUsername(currentRealm, username);
                    Optional<UserModel> userModelOptional = session.userLocalStorage().searchForUserByUserAttributeStream(currentRealm, LDAPConstants.LDAP_ID, ldapUser.getUuid()).findFirst();
                    if (!userModelOptional.isPresent() && currentUserLocal == null) {
                        // Add new user to Keycloak
                        exists.value = false;
                        ldapFedProvider.importUserFromLDAP(session, currentRealm, ldapUser);
                        syncResult.increaseAdded();
                    } else {
                        UserModel currentUser = userModelOptional.isPresent() ? userModelOptional.get() : currentUserLocal;
                        if ((fedModel.getId().equals(currentUser.getFederationLink())) && (ldapUser.getUuid().equals(currentUser.getFirstAttribute(LDAPConstants.LDAP_ID)))) {
                            // Update keycloak user
                            LDAPMappersComparator ldapMappersComparator = new LDAPMappersComparator(ldapFedProvider.getLdapIdentityStore().getConfig());
                            currentRealm.getComponentsStream(fedModel.getId(), LDAPStorageMapper.class.getName()).sorted(ldapMappersComparator.sortDesc()).forEachOrdered(mapperModel -> {
                                LDAPStorageMapper ldapMapper = ldapFedProvider.getMapperManager().getMapper(mapperModel);
                                ldapMapper.onImportUserFromLDAP(ldapUser, currentUser, currentRealm, false);
                            });
                            UserCache userCache = session.userCache();
                            if (userCache != null) {
                                userCache.evict(currentRealm, currentUser);
                            }
                            logger.debugf("Updated user from LDAP: %s", currentUser.getUsername());
                            syncResult.increaseUpdated();
                        } else {
                            logger.warnf("User with ID '%s' is not updated during sync as he already exists in Keycloak database but is not linked to federation provider '%s'", ldapUser.getUuid(), fedModel.getName());
                            syncResult.increaseFailed();
                        }
                    }
                }
            });
        } catch (ModelException me) {
            logger.error("Failed during import user from LDAP", me);
            syncResult.increaseFailed();
            // Remove user if we already added him during this transaction
            if (!exists.value) {
                KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

                    @Override
                    public void run(KeycloakSession session) {
                        LDAPStorageProvider ldapFedProvider = (LDAPStorageProvider) session.getProvider(UserStorageProvider.class, fedModel);
                        RealmModel currentRealm = session.realms().getRealm(realmId);
                        session.getContext().setRealm(currentRealm);
                        String username = null;
                        try {
                            username = LDAPUtils.getUsername(ldapUser, ldapFedProvider.getLdapIdentityStore().getConfig());
                        } catch (ModelException ignore) {
                        }
                        if (username != null) {
                            UserModel existing = session.userLocalStorage().getUserByUsername(currentRealm, username);
                            if (existing != null) {
                                UserCache userCache = session.userCache();
                                if (userCache != null) {
                                    userCache.evict(currentRealm, existing);
                                }
                                session.userLocalStorage().removeUser(currentRealm, existing);
                            }
                        }
                    }
                });
            }
        }
    }
    return syncResult;
}
Also used : SPNEGOAuthenticator(org.keycloak.federation.kerberos.impl.SPNEGOAuthenticator) FullNameLDAPStorageMapperFactory(org.keycloak.storage.ldap.mappers.FullNameLDAPStorageMapperFactory) Date(java.util.Date) LDAPStorageMapper(org.keycloak.storage.ldap.mappers.LDAPStorageMapper) Config(org.keycloak.Config) FullNameLDAPStorageMapper(org.keycloak.storage.ldap.mappers.FullNameLDAPStorageMapper) ProviderConfigurationBuilder(org.keycloak.provider.ProviderConfigurationBuilder) LDAPConstants(org.keycloak.models.LDAPConstants) Map(java.util.Map) ComponentModel(org.keycloak.component.ComponentModel) CredentialRepresentation(org.keycloak.representations.idm.CredentialRepresentation) UserStorageProviderModel(org.keycloak.storage.UserStorageProviderModel) UserAttributeLDAPStorageMapperFactory(org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapperFactory) UserStorageProviderFactory(org.keycloak.storage.UserStorageProviderFactory) HardcodedLDAPAttributeMapper(org.keycloak.storage.ldap.mappers.HardcodedLDAPAttributeMapper) HardcodedLDAPAttributeMapperFactory(org.keycloak.storage.ldap.mappers.HardcodedLDAPAttributeMapperFactory) RealmModel(org.keycloak.models.RealmModel) LDAPConfigDecorator(org.keycloak.storage.ldap.mappers.LDAPConfigDecorator) CredentialHelper(org.keycloak.utils.CredentialHelper) CommonKerberosConfig(org.keycloak.federation.kerberos.CommonKerberosConfig) Collectors(java.util.stream.Collectors) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) ImportSynchronization(org.keycloak.storage.user.ImportSynchronization) List(java.util.List) UserAttributeLDAPStorageMapper(org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapper) KerberosUsernamePasswordAuthenticator(org.keycloak.federation.kerberos.impl.KerberosUsernamePasswordAuthenticator) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) Optional(java.util.Optional) Condition(org.keycloak.storage.ldap.idm.query.Condition) ComponentValidationException(org.keycloak.component.ComponentValidationException) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) Logger(org.jboss.logging.Logger) ProviderConfigProperty(org.keycloak.provider.ProviderConfigProperty) Function(java.util.function.Function) LDAPIdentityStore(org.keycloak.storage.ldap.idm.store.ldap.LDAPIdentityStore) UserModel(org.keycloak.models.UserModel) AuthenticationExecutionModel(org.keycloak.models.AuthenticationExecutionModel) KeycloakSessionTask(org.keycloak.models.KeycloakSessionTask) LDAPQueryConditionsBuilder(org.keycloak.storage.ldap.idm.query.internal.LDAPQueryConditionsBuilder) KerberosConstants(org.keycloak.common.constants.KerberosConstants) UserStorageProvider(org.keycloak.storage.UserStorageProvider) LDAPMappersComparator(org.keycloak.storage.ldap.mappers.LDAPMappersComparator) KerberosServerSubjectAuthenticator(org.keycloak.federation.kerberos.impl.KerberosServerSubjectAuthenticator) KeycloakSession(org.keycloak.models.KeycloakSession) LDAPQuery(org.keycloak.storage.ldap.idm.query.internal.LDAPQuery) UserCache(org.keycloak.models.cache.UserCache) MSADUserAccountControlStorageMapperFactory(org.keycloak.storage.ldap.mappers.msad.MSADUserAccountControlStorageMapperFactory) ModelException(org.keycloak.models.ModelException) SynchronizationResult(org.keycloak.storage.user.SynchronizationResult) LDAPStorageMapper(org.keycloak.storage.ldap.mappers.LDAPStorageMapper) FullNameLDAPStorageMapper(org.keycloak.storage.ldap.mappers.FullNameLDAPStorageMapper) UserAttributeLDAPStorageMapper(org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapper) Optional(java.util.Optional) LDAPMappersComparator(org.keycloak.storage.ldap.mappers.LDAPMappersComparator) ModelException(org.keycloak.models.ModelException) UserCache(org.keycloak.models.cache.UserCache) RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) UserStorageProvider(org.keycloak.storage.UserStorageProvider) KeycloakSessionTask(org.keycloak.models.KeycloakSessionTask) KeycloakSession(org.keycloak.models.KeycloakSession) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) SynchronizationResult(org.keycloak.storage.user.SynchronizationResult)

Example 99 with KeycloakSession

use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.

the class DefaultEvaluation method createRealm.

private Realm createRealm() {
    return new Realm() {

        @Override
        public boolean isUserInGroup(String id, String groupId, boolean checkParent) {
            KeycloakSession session = authorizationProvider.getKeycloakSession();
            UserModel user = getUser(id, session);
            if (Objects.isNull(user)) {
                return false;
            }
            RealmModel realm = session.getContext().getRealm();
            GroupModel group = KeycloakModelUtils.findGroupByPath(realm, groupId);
            if (Objects.isNull(group)) {
                return false;
            }
            if (checkParent) {
                return RoleUtils.isMember(user.getGroupsStream(), group);
            }
            return user.isMemberOf(group);
        }

        private UserModel getUser(String id, KeycloakSession session) {
            RealmModel realm = session.getContext().getRealm();
            UserModel user = session.users().getUserById(realm, id);
            if (Objects.isNull(user)) {
                user = session.users().getUserByUsername(realm, id);
            }
            if (Objects.isNull(user)) {
                user = session.users().getUserByEmail(realm, id);
            }
            if (Objects.isNull(user)) {
                user = session.users().getServiceAccount(realm.getClientById(id));
            }
            return user;
        }

        @Override
        public boolean isUserInRealmRole(String id, String roleName) {
            KeycloakSession session = authorizationProvider.getKeycloakSession();
            UserModel user = getUser(id, session);
            if (Objects.isNull(user)) {
                return false;
            }
            Stream<RoleModel> roleMappings = user.getRoleMappingsStream().filter(isNotClientRole);
            return RoleUtils.hasRole(roleMappings, session.getContext().getRealm().getRole(roleName));
        }

        @Override
        public boolean isUserInClientRole(String id, String clientId, String roleName) {
            KeycloakSession session = authorizationProvider.getKeycloakSession();
            RealmModel realm = session.getContext().getRealm();
            UserModel user = getUser(id, session);
            if (Objects.isNull(user)) {
                return false;
            }
            Set<RoleModel> roleMappings = user.getRoleMappingsStream().filter(RoleModel::isClientRole).filter(role -> Objects.equals(((ClientModel) role.getContainer()).getClientId(), clientId)).collect(Collectors.toSet());
            if (roleMappings.isEmpty()) {
                return false;
            }
            RoleModel role = realm.getClientById(roleMappings.iterator().next().getContainer().getId()).getRole(roleName);
            if (Objects.isNull(role)) {
                return false;
            }
            return RoleUtils.hasRole(roleMappings, role);
        }

        @Override
        public boolean isGroupInRole(String id, String role) {
            KeycloakSession session = authorizationProvider.getKeycloakSession();
            RealmModel realm = session.getContext().getRealm();
            GroupModel group = KeycloakModelUtils.findGroupByPath(realm, id);
            return RoleUtils.hasRoleFromGroup(group, realm.getRole(role), false);
        }

        @Override
        public List<String> getUserRealmRoles(String id) {
            return getUser(id, authorizationProvider.getKeycloakSession()).getRoleMappingsStream().filter(isNotClientRole).map(RoleModel::getName).collect(Collectors.toList());
        }

        @Override
        public List<String> getUserClientRoles(String id, String clientId) {
            return getUser(id, authorizationProvider.getKeycloakSession()).getRoleMappingsStream().filter(RoleModel::isClientRole).map(RoleModel::getName).collect(Collectors.toList());
        }

        @Override
        public List<String> getUserGroups(String id) {
            return getUser(id, authorizationProvider.getKeycloakSession()).getGroupsStream().map(ModelToRepresentation::buildGroupPath).collect(Collectors.toList());
        }

        @Override
        public Map<String, List<String>> getUserAttributes(String id) {
            return Collections.unmodifiableMap(getUser(id, authorizationProvider.getKeycloakSession()).getAttributes());
        }
    };
}
Also used : UserModel(org.keycloak.models.UserModel) RealmModel(org.keycloak.models.RealmModel) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission) ClientModel(org.keycloak.models.ClientModel) java.util(java.util) Effect(org.keycloak.authorization.Decision.Effect) RealmModel(org.keycloak.models.RealmModel) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) Predicate(java.util.function.Predicate) KeycloakSession(org.keycloak.models.KeycloakSession) RoleModel(org.keycloak.models.RoleModel) Decision(org.keycloak.authorization.Decision) Collectors(java.util.stream.Collectors) RoleUtils(org.keycloak.models.utils.RoleUtils) Policy(org.keycloak.authorization.model.Policy) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) Stream(java.util.stream.Stream) UserModel(org.keycloak.models.UserModel) Logic(org.keycloak.representations.idm.authorization.Logic) GroupModel(org.keycloak.models.GroupModel) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) KeycloakSession(org.keycloak.models.KeycloakSession) GroupModel(org.keycloak.models.GroupModel) RoleModel(org.keycloak.models.RoleModel)

Example 100 with KeycloakSession

use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.

the class DirImportProvider method importRealm.

@Override
public void importRealm(KeycloakSessionFactory factory, final String realmName, final Strategy strategy) throws IOException {
    File realmFile = new File(this.rootDirectory + File.separator + realmName + "-realm.json");
    File[] userFiles = this.rootDirectory.listFiles(new FilenameFilter() {

        @Override
        public boolean accept(File dir, String name) {
            return name.matches(realmName + "-users-[0-9]+\\.json");
        }
    });
    File[] federatedUserFiles = this.rootDirectory.listFiles(new FilenameFilter() {

        @Override
        public boolean accept(File dir, String name) {
            return name.matches(realmName + "-federated-users-[0-9]+\\.json");
        }
    });
    // Import realm first
    FileInputStream is = new FileInputStream(realmFile);
    final RealmRepresentation realmRep = JsonSerialization.readValue(is, RealmRepresentation.class);
    final AtomicBoolean realmImported = new AtomicBoolean();
    KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {

        @Override
        public void runExportImportTask(KeycloakSession session) throws IOException {
            boolean imported = ImportUtils.importRealm(session, realmRep, strategy, true);
            realmImported.set(imported);
        }
    });
    if (realmImported.get()) {
        // Import users
        for (final File userFile : userFiles) {
            final FileInputStream fis = new FileInputStream(userFile);
            KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {

                @Override
                protected void runExportImportTask(KeycloakSession session) throws IOException {
                    ImportUtils.importUsersFromStream(session, realmName, JsonSerialization.mapper, fis);
                    logger.infof("Imported users from %s", userFile.getAbsolutePath());
                }
            });
        }
        for (final File userFile : federatedUserFiles) {
            final FileInputStream fis = new FileInputStream(userFile);
            KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {

                @Override
                protected void runExportImportTask(KeycloakSession session) throws IOException {
                    ImportUtils.importFederatedUsersFromStream(session, realmName, JsonSerialization.mapper, fis);
                    logger.infof("Imported federated users from %s", userFile.getAbsolutePath());
                }
            });
        }
    }
    // Import authorization and initialize service accounts last, as they require users already in DB
    KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {

        @Override
        public void runExportImportTask(KeycloakSession session) throws IOException {
            RealmManager realmManager = new RealmManager(session);
            realmManager.setupClientServiceAccountsAndAuthorizationOnImport(realmRep, false);
        }
    });
}
Also used : FilenameFilter(java.io.FilenameFilter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) KeycloakSession(org.keycloak.models.KeycloakSession) IOException(java.io.IOException) RealmManager(org.keycloak.services.managers.RealmManager) ExportImportSessionTask(org.keycloak.exportimport.util.ExportImportSessionTask) File(java.io.File) FileInputStream(java.io.FileInputStream)

Aggregations

KeycloakSession (org.keycloak.models.KeycloakSession)189 RealmModel (org.keycloak.models.RealmModel)136 UserModel (org.keycloak.models.UserModel)78 Test (org.junit.Test)76 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)61 ClientModel (org.keycloak.models.ClientModel)58 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)53 List (java.util.List)34 AtomicReference (java.util.concurrent.atomic.AtomicReference)22 Collectors (java.util.stream.Collectors)21 IOException (java.io.IOException)20 Map (java.util.Map)19 UserSessionModel (org.keycloak.models.UserSessionModel)19 ArrayList (java.util.ArrayList)18 ClientScopeModel (org.keycloak.models.ClientScopeModel)18 RoleModel (org.keycloak.models.RoleModel)18 Set (java.util.Set)16 RealmManager (org.keycloak.services.managers.RealmManager)16 HashMap (java.util.HashMap)14 RealmRepresentation (org.keycloak.representations.idm.RealmRepresentation)14