Search in sources :

Example 51 with ModelException

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

the class HardcodedLDAPRoleStorageMapper method proxy.

@Override
public UserModel proxy(LDAPObject ldapUser, UserModel delegate, RealmModel realm) {
    return new UserModelDelegate(delegate) {

        @Override
        public Stream<RoleModel> getRealmRoleMappingsStream() {
            Stream<RoleModel> realmRoleMappings = super.getRealmRoleMappingsStream();
            RoleModel role = getRole(realm);
            if (role != null && role.getContainer().equals(realm)) {
                realmRoleMappings = Stream.concat(realmRoleMappings, Stream.of(role));
            }
            return realmRoleMappings;
        }

        @Override
        public Stream<RoleModel> getClientRoleMappingsStream(ClientModel app) {
            Stream<RoleModel> clientRoleMappings = super.getClientRoleMappingsStream(app);
            RoleModel role = getRole(realm);
            if (role != null && role.getContainer().equals(app)) {
                return Stream.concat(clientRoleMappings, Stream.of(role));
            }
            return clientRoleMappings;
        }

        @Override
        public boolean hasDirectRole(RoleModel role) {
            return super.hasDirectRole(role) || role.equals(getRole(realm));
        }

        @Override
        public boolean hasRole(RoleModel role) {
            return super.hasRole(role) || role.equals(getRole(realm));
        }

        @Override
        public Stream<RoleModel> getRoleMappingsStream() {
            Stream<RoleModel> roleMappings = super.getRoleMappingsStream();
            RoleModel role = getRole(realm);
            if (role != null) {
                roleMappings = Stream.concat(roleMappings, Stream.of(role));
            }
            return roleMappings;
        }

        @Override
        public void deleteRoleMapping(RoleModel role) {
            if (role.equals(getRole(realm))) {
                throw new ModelException("Not possible to delete role. It's hardcoded by LDAP mapper");
            } else {
                super.deleteRoleMapping(role);
            }
        }
    };
}
Also used : ClientModel(org.keycloak.models.ClientModel) UserModelDelegate(org.keycloak.models.utils.UserModelDelegate) ModelException(org.keycloak.models.ModelException) RoleModel(org.keycloak.models.RoleModel)

Example 52 with ModelException

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

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

the class LDAPIdentityStore method updatePassword.

@Override
public void updatePassword(LDAPObject user, String password, LDAPOperationDecorator passwordUpdateDecorator) {
    String userDN = user.getDn().toString();
    if (logger.isDebugEnabled()) {
        logger.debugf("Using DN [%s] for updating LDAP password of user", userDN);
    }
    if (getConfig().isActiveDirectory()) {
        updateADPassword(userDN, password, passwordUpdateDecorator);
        return;
    }
    try {
        if (config.useExtendedPasswordModifyOp()) {
            operationManager.passwordModifyExtended(userDN, password, passwordUpdateDecorator);
        } else {
            ModificationItem[] mods = new ModificationItem[1];
            BasicAttribute mod0 = new BasicAttribute(LDAPConstants.USER_PASSWORD_ATTRIBUTE, password);
            mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, mod0);
            operationManager.modifyAttributes(userDN, mods, passwordUpdateDecorator);
        }
    } catch (ModelException me) {
        throw me;
    } catch (Exception e) {
        throw new ModelException("Error updating password.", e);
    }
}
Also used : BasicAttribute(javax.naming.directory.BasicAttribute) ModificationItem(javax.naming.directory.ModificationItem) ModelException(org.keycloak.models.ModelException) 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 54 with ModelException

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

the class LDAPIdentityStore method removeMemberFromGroup.

@Override
public void removeMemberFromGroup(String groupDn, String memberAttrName, String value) {
    BasicAttribute attr = new BasicAttribute(memberAttrName, value);
    ModificationItem item = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, attr);
    try {
        this.operationManager.modifyAttributesNaming(groupDn, new ModificationItem[] { item }, null);
    } catch (NoSuchAttributeException e) {
        logger.debugf("Group %s does not contain the member %s", groupDn, value);
    } catch (SchemaViolationException e) {
        // schema violation removing one member => add the empty attribute, it cannot be other thing
        logger.infof("Schema violation in group %s removing member %s. Trying adding empty member attribute.", groupDn, value);
        try {
            this.operationManager.modifyAttributesNaming(groupDn, new ModificationItem[] { item, new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute(memberAttrName, LDAPConstants.EMPTY_MEMBER_ATTRIBUTE_VALUE)) }, null);
        } catch (NamingException ex) {
            throw new ModelException("Could not modify attribute for DN [" + groupDn + "]", ex);
        }
    } catch (NamingException e) {
        throw new ModelException("Could not modify attribute for DN [" + groupDn + "]", e);
    }
}
Also used : BasicAttribute(javax.naming.directory.BasicAttribute) ModificationItem(javax.naming.directory.ModificationItem) NoSuchAttributeException(javax.naming.directory.NoSuchAttributeException) ModelException(org.keycloak.models.ModelException) NamingException(javax.naming.NamingException) SchemaViolationException(javax.naming.directory.SchemaViolationException)

Example 55 with ModelException

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

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