Search in sources :

Example 46 with ModelException

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

the class LDAPUserLoginTest method afterImportTestRealm.

@Override
protected void afterImportTestRealm() {
    try {
        getTestingClient().server().run(session -> {
            LDAPTestContext ctx = LDAPTestContext.init(session);
            RealmModel appRealm = ctx.getRealm();
            // Delete all LDAP users
            LDAPTestUtils.removeAllLDAPUsers(ctx.getLdapProvider(), appRealm);
            // Add some new LDAP users for testing
            LDAPObject john = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, DEFAULT_TEST_USERS.get("VALID_USER_NAME"), DEFAULT_TEST_USERS.get("VALID_USER_FIRST_NAME"), DEFAULT_TEST_USERS.get("VALID_USER_LAST_NAME"), DEFAULT_TEST_USERS.get("VALID_USER_EMAIL"), DEFAULT_TEST_USERS.get("VALID_USER_STREET"), DEFAULT_TEST_USERS.get("VALID_USER_POSTAL_CODE"));
            LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), john, DEFAULT_TEST_USERS.get("VALID_USER_PASSWORD"));
        });
    } catch (RunOnServerException ex) {
        Assume.assumeFalse("Work around JDK-8214440", ex.getCause() instanceof ModelException && ex.getCause().getCause() instanceof ModelException && ex.getCause().getCause().getCause() instanceof javax.naming.AuthenticationException && Objects.equals(ex.getCause().getCause().getCause().getMessage(), "Could not negotiate TLS"));
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) ModelException(org.keycloak.models.ModelException) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) RunOnServerException(org.keycloak.testsuite.runonserver.RunOnServerException)

Example 47 with ModelException

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

the class LDAPProvidersIntegrationTest method testHardcodedRoleMapper.

@Test
public void testHardcodedRoleMapper() {
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        RoleModel hardcodedRole = appRealm.addRole("hardcoded-role");
        // assert that user "johnkeycloak" doesn't have hardcoded role
        UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak");
        Assert.assertFalse(john.hasRole(hardcodedRole));
        ComponentModel hardcodedMapperModel = KeycloakModelUtils.createComponentModel("hardcoded role", ctx.getLdapModel().getId(), HardcodedLDAPRoleStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(), HardcodedLDAPRoleStorageMapper.ROLE, "hardcoded-role");
        appRealm.addComponentModel(hardcodedMapperModel);
    });
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        RoleModel hardcodedRole = appRealm.getRole("hardcoded-role");
        // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName
        UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak");
        Assert.assertTrue(john.hasRole(hardcodedRole));
        // Can't remove user from hardcoded role
        try {
            john.deleteRoleMapping(hardcodedRole);
            Assert.fail("Didn't expected to remove role mapping");
        } catch (ModelException expected) {
        }
        // Revert mappers
        ComponentModel hardcodedMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "hardcoded role");
        appRealm.removeComponent(hardcodedMapperModel);
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) CachedUserModel(org.keycloak.models.cache.CachedUserModel) UserModel(org.keycloak.models.UserModel) LDAPStorageMapper(org.keycloak.storage.ldap.mappers.LDAPStorageMapper) UserAttributeLDAPStorageMapper(org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapper) ModelException(org.keycloak.models.ModelException) ComponentModel(org.keycloak.component.ComponentModel) RoleModel(org.keycloak.models.RoleModel) AbstractAuthTest(org.keycloak.testsuite.AbstractAuthTest) Test(org.junit.Test)

Example 48 with ModelException

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

the class LDAPProvidersIntegrationTest method testHardcodedGroupMapper.

@Test
public void testHardcodedGroupMapper() {
    final String uuid = UUID.randomUUID().toString();
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        GroupModel hardcodedGroup = appRealm.createGroup(uuid, "hardcoded-group");
        // assert that user "johnkeycloak" doesn't have hardcoded group
        UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak");
        Assert.assertFalse(john.isMemberOf(hardcodedGroup));
        ComponentModel hardcodedMapperModel = KeycloakModelUtils.createComponentModel("hardcoded group", ctx.getLdapModel().getId(), HardcodedLDAPGroupStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(), HardcodedLDAPGroupStorageMapper.GROUP, "hardcoded-group");
        appRealm.addComponentModel(hardcodedMapperModel);
    });
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        GroupModel hardcodedGroup = appRealm.getGroupById(uuid);
        // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName
        UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak");
        Assert.assertTrue(john.isMemberOf(hardcodedGroup));
        // Can't remove user from hardcoded role
        try {
            john.leaveGroup(hardcodedGroup);
            Assert.fail("Didn't expected to leave group");
        } catch (ModelException expected) {
        }
        // Revert mappers
        ComponentModel hardcodedMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "hardcoded group");
        appRealm.removeComponent(hardcodedMapperModel);
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) CachedUserModel(org.keycloak.models.cache.CachedUserModel) UserModel(org.keycloak.models.UserModel) LDAPStorageMapper(org.keycloak.storage.ldap.mappers.LDAPStorageMapper) UserAttributeLDAPStorageMapper(org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapper) ModelException(org.keycloak.models.ModelException) ComponentModel(org.keycloak.component.ComponentModel) GroupModel(org.keycloak.models.GroupModel) AbstractAuthTest(org.keycloak.testsuite.AbstractAuthTest) Test(org.junit.Test)

Example 49 with ModelException

use of org.keycloak.models.ModelException 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 50 with ModelException

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

the class LDAPUtils method computeAndSetDn.

// ldapUser has filled attributes, but doesn't have filled dn.
public static void computeAndSetDn(LDAPConfig config, LDAPObject ldapUser) {
    String rdnLdapAttrName = config.getRdnLdapAttribute();
    String rdnLdapAttrValue = ldapUser.getAttributeAsString(rdnLdapAttrName);
    if (rdnLdapAttrValue == null) {
        throw new ModelException("RDN Attribute [" + rdnLdapAttrName + "] is not filled. Filled attributes: " + ldapUser.getAttributes());
    }
    LDAPDn dn = LDAPDn.fromString(config.getUsersDn());
    dn.addFirst(rdnLdapAttrName, rdnLdapAttrValue);
    ldapUser.setDn(dn);
}
Also used : ModelException(org.keycloak.models.ModelException) LDAPDn(org.keycloak.storage.ldap.idm.model.LDAPDn)

Aggregations

ModelException (org.keycloak.models.ModelException)74 RealmModel (org.keycloak.models.RealmModel)20 NamingException (javax.naming.NamingException)13 UserModel (org.keycloak.models.UserModel)13 ClientModel (org.keycloak.models.ClientModel)11 ComponentModel (org.keycloak.component.ComponentModel)10 LDAPObject (org.keycloak.storage.ldap.idm.model.LDAPObject)10 IOException (java.io.IOException)9 Consumes (javax.ws.rs.Consumes)9 NotFoundException (javax.ws.rs.NotFoundException)8 BasicAttribute (javax.naming.directory.BasicAttribute)7 KeycloakSession (org.keycloak.models.KeycloakSession)7 RoleModel (org.keycloak.models.RoleModel)7 ErrorResponseException (org.keycloak.services.ErrorResponseException)7 ReadOnlyException (org.keycloak.storage.ReadOnlyException)7 POST (javax.ws.rs.POST)6 Path (javax.ws.rs.Path)6 Test (org.junit.Test)6 ArrayList (java.util.ArrayList)5 AttributeInUseException (javax.naming.directory.AttributeInUseException)5