Search in sources :

Example 61 with LDAPObject

use of org.keycloak.storage.ldap.idm.model.LDAPObject in project keycloak by keycloak.

the class LDAPStorageProvider method removeUser.

@Override
public boolean removeUser(RealmModel realm, UserModel user) {
    if (editMode == UserStorageProvider.EditMode.READ_ONLY || editMode == UserStorageProvider.EditMode.UNSYNCED) {
        logger.warnf("User '%s' can't be deleted in LDAP as editMode is '%s'. Deleting user just from Keycloak DB, but he will be re-imported from LDAP again once searched in Keycloak", user.getUsername(), editMode.toString());
        return true;
    }
    LDAPObject ldapObject = loadAndValidateUser(realm, user);
    if (ldapObject == null) {
        logger.warnf("User '%s' can't be deleted from LDAP as it doesn't exist here", user.getUsername());
        return false;
    }
    ldapIdentityStore.remove(ldapObject);
    userManager.removeManagedUserEntry(user.getId());
    return true;
}
Also used : LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject)

Example 62 with LDAPObject

use of org.keycloak.storage.ldap.idm.model.LDAPObject in project keycloak by keycloak.

the class LDAPStorageProvider method loadLDAPUserByUsername.

public LDAPObject loadLDAPUserByUsername(RealmModel realm, String username) {
    try (LDAPQuery ldapQuery = LDAPUtils.createQueryForUserSearch(this, realm)) {
        LDAPQueryConditionsBuilder conditionsBuilder = new LDAPQueryConditionsBuilder();
        String usernameMappedAttribute = this.ldapIdentityStore.getConfig().getUsernameLdapAttribute();
        Condition usernameCondition = conditionsBuilder.equal(usernameMappedAttribute, username, EscapeStrategy.DEFAULT);
        ldapQuery.addWhereCondition(usernameCondition);
        LDAPObject ldapUser = ldapQuery.getFirstResult();
        if (ldapUser == null) {
            return null;
        }
        return ldapUser;
    }
}
Also used : Condition(org.keycloak.storage.ldap.idm.query.Condition) LDAPQuery(org.keycloak.storage.ldap.idm.query.internal.LDAPQuery) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) LDAPQueryConditionsBuilder(org.keycloak.storage.ldap.idm.query.internal.LDAPQueryConditionsBuilder)

Example 63 with LDAPObject

use of org.keycloak.storage.ldap.idm.model.LDAPObject in project keycloak by keycloak.

the class LDAPIdentityStore method populateAttributedType.

private LDAPObject populateAttributedType(SearchResult searchResult, LDAPQuery ldapQuery) {
    Set<String> readOnlyAttrNames = ldapQuery.getReturningReadOnlyLdapAttributes();
    Set<String> lowerCasedAttrNames = new TreeSet<>();
    for (String attrName : ldapQuery.getReturningLdapAttributes()) {
        lowerCasedAttrNames.add(attrName.toLowerCase());
    }
    try {
        String entryDN = searchResult.getNameInNamespace();
        Attributes attributes = searchResult.getAttributes();
        LDAPObject ldapObject = new LDAPObject();
        LDAPDn dn = LDAPDn.fromString(entryDN);
        ldapObject.setDn(dn);
        ldapObject.setRdnAttributeNames(dn.getFirstRdn().getAllKeys());
        NamingEnumeration<? extends Attribute> ldapAttributes = attributes.getAll();
        while (ldapAttributes.hasMore()) {
            Attribute ldapAttribute = ldapAttributes.next();
            try {
                ldapAttribute.get();
            } catch (NoSuchElementException nsee) {
                continue;
            }
            String ldapAttributeName = ldapAttribute.getID();
            // check for ranged attribute
            Matcher m = rangePattern.matcher(ldapAttributeName);
            if (m.matches()) {
                ldapAttributeName = m.group(1);
                // range=X-* means all the attributes returned
                if (!m.group(3).equals("*")) {
                    try {
                        int max = Integer.parseInt(m.group(3));
                        ldapObject.addRangedAttribute(ldapAttributeName, max);
                    } catch (NumberFormatException e) {
                        logger.warnf("Invalid ranged expresion for attribute: %s", m.group(0));
                    }
                }
            }
            if (ldapAttributeName.equalsIgnoreCase(getConfig().getUuidLDAPAttributeName())) {
                Object uuidValue = ldapAttribute.get();
                ldapObject.setUuid(this.operationManager.decodeEntryUUID(uuidValue));
            }
            // Note: UUID is normally not populated here. It's populated just in case that it's used for name of other attribute as well
            if (!ldapAttributeName.equalsIgnoreCase(getConfig().getUuidLDAPAttributeName()) || (lowerCasedAttrNames.contains(ldapAttributeName.toLowerCase()))) {
                Set<String> attrValues = new LinkedHashSet<>();
                NamingEnumeration<?> enumm = ldapAttribute.getAll();
                while (enumm.hasMoreElements()) {
                    Object val = enumm.next();
                    if (val instanceof byte[]) {
                        // byte[]
                        String attrVal = Base64.encodeBytes((byte[]) val);
                        attrValues.add(attrVal);
                    } else {
                        // String
                        String attrVal = val.toString().trim();
                        attrValues.add(attrVal);
                    }
                }
                if (ldapAttributeName.equalsIgnoreCase(LDAPConstants.OBJECT_CLASS)) {
                    ldapObject.setObjectClasses(attrValues);
                } else {
                    ldapObject.setAttribute(ldapAttributeName, attrValues);
                    // readOnlyAttrNames are lower-cased
                    if (readOnlyAttrNames.contains(ldapAttributeName.toLowerCase())) {
                        ldapObject.addReadOnlyAttributeName(ldapAttributeName);
                    }
                }
            }
        }
        if (logger.isTraceEnabled()) {
            logger.tracef("Found ldap object and populated with the attributes. LDAP Object: %s", ldapObject.toString());
        }
        return ldapObject;
    } catch (Exception e) {
        throw new ModelException("Could not populate attribute type " + searchResult.getNameInNamespace() + ".", e);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ModelException(org.keycloak.models.ModelException) BasicAttribute(javax.naming.directory.BasicAttribute) Attribute(javax.naming.directory.Attribute) Matcher(java.util.regex.Matcher) BasicAttributes(javax.naming.directory.BasicAttributes) Attributes(javax.naming.directory.Attributes) NamingException(javax.naming.NamingException) AuthenticationException(javax.naming.AuthenticationException) AttributeInUseException(javax.naming.directory.AttributeInUseException) NoSuchAttributeException(javax.naming.directory.NoSuchAttributeException) NoSuchElementException(java.util.NoSuchElementException) IOException(java.io.IOException) ModelException(org.keycloak.models.ModelException) SchemaViolationException(javax.naming.directory.SchemaViolationException) TreeSet(java.util.TreeSet) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) LDAPDn(org.keycloak.storage.ldap.idm.model.LDAPDn) NoSuchElementException(java.util.NoSuchElementException)

Example 64 with LDAPObject

use of org.keycloak.storage.ldap.idm.model.LDAPObject in project keycloak by keycloak.

the class LDAPIdentityStore method fetchQueryResults.

@Override
public List<LDAPObject> fetchQueryResults(LDAPQuery identityQuery) {
    if (identityQuery.getSorting() != null && !identityQuery.getSorting().isEmpty()) {
        throw new ModelException("LDAP Identity Store does not yet support sorted queries.");
    }
    List<LDAPObject> results = new ArrayList<>();
    try {
        String baseDN = identityQuery.getSearchDn();
        for (Condition condition : identityQuery.getConditions()) {
            // Check if we are searching by ID
            String uuidAttrName = getConfig().getUuidLDAPAttributeName();
            if (condition instanceof EqualCondition) {
                EqualCondition equalCondition = (EqualCondition) condition;
                if (equalCondition.getParameterName().equalsIgnoreCase(uuidAttrName)) {
                    SearchResult search = this.operationManager.lookupById(baseDN, equalCondition.getValue().toString(), identityQuery.getReturningLdapAttributes());
                    if (search != null) {
                        results.add(populateAttributedType(search, identityQuery));
                    }
                    return results;
                }
            }
        }
        StringBuilder filter = createIdentityTypeSearchFilter(identityQuery);
        List<SearchResult> search;
        if (getConfig().isPagination() && identityQuery.getLimit() > 0) {
            search = this.operationManager.searchPaginated(baseDN, filter.toString(), identityQuery);
        } else {
            search = this.operationManager.search(baseDN, filter.toString(), identityQuery.getReturningLdapAttributes(), identityQuery.getSearchScope());
        }
        for (SearchResult result : search) {
            // don't add the branch in subtree search
            if (identityQuery.getSearchScope() != SearchControls.SUBTREE_SCOPE || !result.getNameInNamespace().equalsIgnoreCase(baseDN)) {
                results.add(populateAttributedType(result, identityQuery));
            }
        }
    } catch (Exception e) {
        throw new ModelException("Querying of LDAP failed " + identityQuery, e);
    }
    return results;
}
Also used : EqualCondition(org.keycloak.storage.ldap.idm.query.internal.EqualCondition) Condition(org.keycloak.storage.ldap.idm.query.Condition) ModelException(org.keycloak.models.ModelException) ArrayList(java.util.ArrayList) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) SearchResult(javax.naming.directory.SearchResult) EqualCondition(org.keycloak.storage.ldap.idm.query.internal.EqualCondition) NamingException(javax.naming.NamingException) AuthenticationException(javax.naming.AuthenticationException) AttributeInUseException(javax.naming.directory.AttributeInUseException) NoSuchAttributeException(javax.naming.directory.NoSuchAttributeException) NoSuchElementException(java.util.NoSuchElementException) IOException(java.io.IOException) ModelException(org.keycloak.models.ModelException) SchemaViolationException(javax.naming.directory.SchemaViolationException)

Example 65 with LDAPObject

use of org.keycloak.storage.ldap.idm.model.LDAPObject in project keycloak by keycloak.

the class GroupLDAPStorageMapper method processKeycloakGroupSyncToLDAP.

// For given kcGroup check if it exists in LDAP (map) by name
// If not, create it in LDAP including attributes. Otherwise update attributes in LDAP.
// Process this recursively for all subgroups of KC group
private void processKeycloakGroupSyncToLDAP(GroupModel kcGroup, Map<String, LDAPObject> ldapGroupsMap, Set<String> ldapGroupNames, SynchronizationResult syncResult) {
    String groupName = kcGroup.getName();
    // extract group attributes to be updated to LDAP
    Map<String, Set<String>> supportedLdapAttributes = new HashMap<>();
    for (String attrName : config.getGroupAttributes()) {
        Set<String> valueSet = kcGroup.getAttributeStream(attrName).collect(Collectors.toSet());
        supportedLdapAttributes.put(attrName, valueSet.isEmpty() ? null : valueSet);
    }
    LDAPObject ldapGroup = ldapGroupsMap.get(groupName);
    if (ldapGroup == null) {
        ldapGroup = createLDAPGroup(groupName, supportedLdapAttributes);
        syncResult.increaseAdded();
    } else {
        for (Map.Entry<String, Set<String>> attrEntry : supportedLdapAttributes.entrySet()) {
            ldapGroup.setAttribute(attrEntry.getKey(), attrEntry.getValue());
        }
        ldapProvider.getLdapIdentityStore().update(ldapGroup);
        syncResult.increaseUpdated();
    }
    ldapGroupsMap.put(groupName, ldapGroup);
    ldapGroupNames.add(groupName);
    // process KC subgroups
    kcGroup.getSubGroupsStream().forEach(kcSubgroup -> processKeycloakGroupSyncToLDAP(kcSubgroup, ldapGroupsMap, ldapGroupNames, syncResult));
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

LDAPObject (org.keycloak.storage.ldap.idm.model.LDAPObject)105 RealmModel (org.keycloak.models.RealmModel)61 Test (org.junit.Test)38 LDAPStorageProvider (org.keycloak.storage.ldap.LDAPStorageProvider)37 ComponentModel (org.keycloak.component.ComponentModel)35 UserModel (org.keycloak.models.UserModel)28 GroupModel (org.keycloak.models.GroupModel)18 SynchronizationResult (org.keycloak.storage.user.SynchronizationResult)16 GroupLDAPStorageMapper (org.keycloak.storage.ldap.mappers.membership.group.GroupLDAPStorageMapper)14 ModelException (org.keycloak.models.ModelException)11 LDAPDn (org.keycloak.storage.ldap.idm.model.LDAPDn)10 LDAPQuery (org.keycloak.storage.ldap.idm.query.internal.LDAPQuery)10 HashMap (java.util.HashMap)9 AbstractAuthTest (org.keycloak.testsuite.AbstractAuthTest)8 HashSet (java.util.HashSet)7 List (java.util.List)7 CachedUserModel (org.keycloak.models.cache.CachedUserModel)7 LDAPConfig (org.keycloak.storage.ldap.LDAPConfig)7 LDAPStorageMapper (org.keycloak.storage.ldap.mappers.LDAPStorageMapper)7 Map (java.util.Map)6