Search in sources :

Example 76 with ComponentModel

use of org.keycloak.component.ComponentModel in project keycloak by keycloak.

the class UserProfileTest method testCustomAttributeRequired.

private static void testCustomAttributeRequired(KeycloakSession session) throws IOException {
    DeclarativeUserProfileProvider provider = getDynamicUserProfileProvider(session);
    ComponentModel component = provider.getComponentModel();
    assertNotNull(component);
    UPConfig config = new UPConfig();
    UPAttribute attribute = new UPAttribute();
    attribute.setName(ATT_ADDRESS);
    Map<String, Object> validatorConfig = new HashMap<>();
    validatorConfig.put(LengthValidator.KEY_MIN, 4);
    attribute.addValidation(LengthValidator.ID, validatorConfig);
    // make it ALWAYS required
    UPAttributeRequired requirements = new UPAttributeRequired();
    attribute.setRequired(requirements);
    UPAttributePermissions permissions = new UPAttributePermissions();
    permissions.setEdit(Collections.singleton(ROLE_USER));
    attribute.setPermissions(permissions);
    config.addAttribute(attribute);
    provider.setConfiguration(JsonSerialization.writeValueAsString(config));
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(UserModel.USERNAME, "user");
    UserProfile profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes);
    // fails on required validation
    try {
        profile.validate();
        fail("Should fail validation");
    } catch (ValidationException ve) {
        assertTrue(ve.isAttributeOnError(ATT_ADDRESS));
    }
    // fails on length validation
    attributes.put(ATT_ADDRESS, "adr");
    profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes);
    try {
        profile.validate();
        fail("Should fail validation");
    } catch (ValidationException ve) {
        assertTrue(ve.isAttributeOnError(ATT_ADDRESS));
    }
    // all OK
    attributes.put(ATT_ADDRESS, "adress ok");
    attributes.put(UserModel.FIRST_NAME, "Joe");
    attributes.put(UserModel.LAST_NAME, "Doe");
    profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes);
    profile.validate();
}
Also used : UPAttributePermissions(org.keycloak.userprofile.config.UPAttributePermissions) ComponentValidationException(org.keycloak.component.ComponentValidationException) ValidationException(org.keycloak.userprofile.ValidationException) UserProfile(org.keycloak.userprofile.UserProfile) HashMap(java.util.HashMap) DeclarativeUserProfileProvider(org.keycloak.userprofile.DeclarativeUserProfileProvider) UPConfig(org.keycloak.userprofile.config.UPConfig) ComponentModel(org.keycloak.component.ComponentModel) UPAttributeRequired(org.keycloak.userprofile.config.UPAttributeRequired) UPAttribute(org.keycloak.userprofile.config.UPAttribute)

Example 77 with ComponentModel

use of org.keycloak.component.ComponentModel in project keycloak by keycloak.

the class UserProfileTest method testCustomAttributeOptional.

private static void testCustomAttributeOptional(KeycloakSession session) throws IOException {
    DeclarativeUserProfileProvider provider = getDynamicUserProfileProvider(session);
    ComponentModel component = provider.getComponentModel();
    assertNotNull(component);
    UPConfig config = new UPConfig();
    UPAttribute attribute = new UPAttribute();
    attribute.setName(ATT_ADDRESS);
    Map<String, Object> validatorConfig = new HashMap<>();
    validatorConfig.put(LengthValidator.KEY_MIN, 4);
    attribute.addValidation(LengthValidator.ID, validatorConfig);
    config.addAttribute(attribute);
    provider.setConfiguration(JsonSerialization.writeValueAsString(config));
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(UserModel.USERNAME, "user");
    // null is OK as attribute is optional
    UserProfile profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes);
    profile.validate();
    // blank String have to be OK as it is what UI forms send for not filled in optional attributes
    attributes.put(ATT_ADDRESS, "");
    profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes);
    profile.validate();
    // fails on length validation
    attributes.put(ATT_ADDRESS, "adr");
    profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes);
    try {
        profile.validate();
        fail("Should fail validation");
    } catch (ValidationException ve) {
        assertTrue(ve.isAttributeOnError(ATT_ADDRESS));
    }
    // all OK
    attributes.put(ATT_ADDRESS, "adress ok");
    profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes);
    profile.validate();
}
Also used : ComponentValidationException(org.keycloak.component.ComponentValidationException) ValidationException(org.keycloak.userprofile.ValidationException) UserProfile(org.keycloak.userprofile.UserProfile) HashMap(java.util.HashMap) DeclarativeUserProfileProvider(org.keycloak.userprofile.DeclarativeUserProfileProvider) UPConfig(org.keycloak.userprofile.config.UPConfig) ComponentModel(org.keycloak.component.ComponentModel) UPAttribute(org.keycloak.userprofile.config.UPAttribute)

Example 78 with ComponentModel

use of org.keycloak.component.ComponentModel in project keycloak by keycloak.

the class UserProfileTest method testCustomValidationForUsername.

private static void testCustomValidationForUsername(KeycloakSession session) throws IOException {
    DeclarativeUserProfileProvider provider = getDynamicUserProfileProvider(session);
    ComponentModel component = provider.getComponentModel();
    assertNotNull(component);
    UPConfig config = new UPConfig();
    UPAttribute attribute = new UPAttribute();
    attribute.setName(UserModel.USERNAME);
    Map<String, Object> validatorConfig = new HashMap<>();
    validatorConfig.put("min", 4);
    attribute.addValidation(LengthValidator.ID, validatorConfig);
    config.addAttribute(attribute);
    provider.setConfiguration(JsonSerialization.writeValueAsString(config));
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(UserModel.USERNAME, "us");
    UserProfile profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes);
    try {
        profile.validate();
        fail("Should fail validation");
    } catch (ValidationException ve) {
        assertTrue(ve.isAttributeOnError(UserModel.USERNAME));
        assertTrue(ve.hasError(LengthValidator.MESSAGE_INVALID_LENGTH_TOO_SHORT));
    }
    attributes.put(UserModel.USERNAME, "user");
    profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes);
    profile.validate();
    provider.setConfiguration(null);
    attributes.put(UserModel.USERNAME, "user");
    attributes.put(UserModel.FIRST_NAME, "Joe");
    attributes.put(UserModel.LAST_NAME, "Doe");
    profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes);
    profile.validate();
}
Also used : ComponentValidationException(org.keycloak.component.ComponentValidationException) ValidationException(org.keycloak.userprofile.ValidationException) UserProfile(org.keycloak.userprofile.UserProfile) HashMap(java.util.HashMap) DeclarativeUserProfileProvider(org.keycloak.userprofile.DeclarativeUserProfileProvider) UPConfig(org.keycloak.userprofile.config.UPConfig) ComponentModel(org.keycloak.component.ComponentModel) UPAttribute(org.keycloak.userprofile.config.UPAttribute)

Example 79 with ComponentModel

use of org.keycloak.component.ComponentModel in project keycloak by keycloak.

the class UserProfileTest method testRequiredIfUser.

private static void testRequiredIfUser(KeycloakSession session) throws IOException {
    DeclarativeUserProfileProvider provider = getDynamicUserProfileProvider(session);
    ComponentModel component = provider.getComponentModel();
    assertNotNull(component);
    UPConfig config = new UPConfig();
    UPAttribute attribute = new UPAttribute();
    attribute.setName(ATT_ADDRESS);
    UPAttributeRequired requirements = new UPAttributeRequired();
    requirements.setRoles(Collections.singleton(ROLE_USER));
    attribute.setRequired(requirements);
    UPAttributePermissions permissions = new UPAttributePermissions();
    permissions.setEdit(Collections.singleton(ROLE_USER));
    attribute.setPermissions(permissions);
    config.addAttribute(attribute);
    provider.setConfiguration(JsonSerialization.writeValueAsString(config));
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(UserModel.USERNAME, "user");
    // fail on common contexts
    UserProfile profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes);
    try {
        profile.validate();
        fail("Should fail validation");
    } catch (ValidationException ve) {
        assertTrue(ve.isAttributeOnError(ATT_ADDRESS));
    }
    profile = provider.create(UserProfileContext.ACCOUNT, attributes);
    try {
        profile.validate();
        fail("Should fail validation");
    } catch (ValidationException ve) {
        assertTrue(ve.isAttributeOnError(ATT_ADDRESS));
    }
    profile = provider.create(UserProfileContext.REGISTRATION_PROFILE, attributes);
    try {
        profile.validate();
        fail("Should fail validation");
    } catch (ValidationException ve) {
        assertTrue(ve.isAttributeOnError(ATT_ADDRESS));
    }
    attributes.put(UserModel.FIRST_NAME, "Joe");
    attributes.put(UserModel.LAST_NAME, "Doe");
    // no fail on User API
    profile = provider.create(UserProfileContext.USER_API, attributes);
    profile.validate();
}
Also used : UPAttributePermissions(org.keycloak.userprofile.config.UPAttributePermissions) ComponentValidationException(org.keycloak.component.ComponentValidationException) ValidationException(org.keycloak.userprofile.ValidationException) UserProfile(org.keycloak.userprofile.UserProfile) HashMap(java.util.HashMap) DeclarativeUserProfileProvider(org.keycloak.userprofile.DeclarativeUserProfileProvider) UPConfig(org.keycloak.userprofile.config.UPConfig) ComponentModel(org.keycloak.component.ComponentModel) UPAttributeRequired(org.keycloak.userprofile.config.UPAttributeRequired) UPAttribute(org.keycloak.userprofile.config.UPAttribute)

Example 80 with ComponentModel

use of org.keycloak.component.ComponentModel 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)

Aggregations

ComponentModel (org.keycloak.component.ComponentModel)155 RealmModel (org.keycloak.models.RealmModel)74 Test (org.junit.Test)52 LDAPStorageProvider (org.keycloak.storage.ldap.LDAPStorageProvider)46 LDAPObject (org.keycloak.storage.ldap.idm.model.LDAPObject)34 UserModel (org.keycloak.models.UserModel)29 HashMap (java.util.HashMap)22 UserStorageProviderModel (org.keycloak.storage.UserStorageProviderModel)22 GroupModel (org.keycloak.models.GroupModel)21 MultivaluedHashMap (org.keycloak.common.util.MultivaluedHashMap)18 SynchronizationResult (org.keycloak.storage.user.SynchronizationResult)18 ComponentValidationException (org.keycloak.component.ComponentValidationException)16 UserStorageProvider (org.keycloak.storage.UserStorageProvider)16 LDAPStorageMapper (org.keycloak.storage.ldap.mappers.LDAPStorageMapper)15 GroupLDAPStorageMapper (org.keycloak.storage.ldap.mappers.membership.group.GroupLDAPStorageMapper)15 Path (javax.ws.rs.Path)14 DeclarativeUserProfileProvider (org.keycloak.userprofile.DeclarativeUserProfileProvider)13 ModelException (org.keycloak.models.ModelException)11 UPAttribute (org.keycloak.userprofile.config.UPAttribute)11 UPConfig (org.keycloak.userprofile.config.UPConfig)11