Search in sources :

Example 31 with SearchControls

use of javax.naming.directory.SearchControls in project simba-os by cegeka.

the class ActiveDirectoryLoginModule method addADGroupsToUser.

protected void addADGroupsToUser(LdapContext ldapContext, User user, String userCN) throws NamingException {
    SearchControls searchControls = new SearchControls();
    searchControls.setReturningAttributes(new String[] { "dn" });
    searchControls.setSearchScope(searchScope);
    GroupRepository groupRepository = GlobalContext.locate(GroupRepository.class);
    String filterGroups = "(&(member=" + userCN + "," + searchBase + ")(objectcategory=group))";
    NamingEnumeration results = ldapContext.search(searchBase, filterGroups, searchControls);
    while (hasMoreResults(results)) {
        String groupCN = ((SearchResult) results.next()).getName();
        Group group = groupRepository.findByCN(groupCN);
        if (group != null) {
            user.addGroup(group);
        }
    }
}
Also used : Group(org.simbasecurity.core.domain.Group) SearchControls(javax.naming.directory.SearchControls) NamingEnumeration(javax.naming.NamingEnumeration) SearchResult(javax.naming.directory.SearchResult) GroupRepository(org.simbasecurity.core.domain.repository.GroupRepository)

Example 32 with SearchControls

use of javax.naming.directory.SearchControls in project fess by codelibs.

the class LdapManager method search.

protected void search(final String baseDn, final String filter, final String[] returningAttrs, final Supplier<Hashtable<String, String>> envSupplier, final SearcConsumer consumer) {
    try (DirContextHolder holder = getDirContext(envSupplier)) {
        final SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        if (returningAttrs != null) {
            controls.setReturningAttributes(returningAttrs);
        }
        consumer.accept(Collections.list(holder.get().search(baseDn, filter, controls)));
    } catch (final NamingException e) {
        throw new LdapOperationException("Failed to search " + baseDn + " with " + filter, e);
    }
}
Also used : LdapOperationException(org.codelibs.fess.exception.LdapOperationException) SearchControls(javax.naming.directory.SearchControls) NamingException(javax.naming.NamingException)

Example 33 with SearchControls

use of javax.naming.directory.SearchControls in project Lucee by lucee.

the class LDAPClient method query.

/**
 * @param dn
 * @param strAttributes
 * @param scope
 * @param startrow
 * @param maxrows
 * @param timeout
 * @param sort
 * @param sortType
 * @param sortDirection
 * @param start
 * @param separator
 * @param filter
 * @return
 * @throws NamingException
 * @throws PageException
 * @throws IOException
 */
public Query query(String strAttributes, int scope, int startrow, int maxrows, int timeout, String[] sort, int sortType, int sortDirection, String start, String separator, String filter) throws NamingException, PageException, IOException {
    // strAttributes=strAttributes.trim();
    boolean attEQAsterix = strAttributes.trim().equals("*");
    String[] attributes = attEQAsterix ? new String[] { "name", "value" } : toStringAttributes(strAttributes, ",");
    // Control
    SearchControls controls = new SearchControls();
    controls.setReturningObjFlag(true);
    controls.setSearchScope(scope);
    if (!attEQAsterix)
        controls.setReturningAttributes(toStringAttributes(strAttributes, ","));
    if (maxrows > 0)
        controls.setCountLimit(startrow + maxrows + 1);
    if (timeout > 0)
        controls.setTimeLimit(timeout);
    InitialLdapContext context = new InitialLdapContext(env, null);
    // Search
    Query qry = new QueryImpl(attributes, 0, "query");
    try {
        NamingEnumeration results = context.search(start, filter, controls);
        // Fill result
        int row = 1;
        if (!attEQAsterix) {
            while (results.hasMoreElements()) {
                SearchResult resultRow = (SearchResult) results.next();
                if (row++ < startrow)
                    continue;
                int len = qry.addRow();
                NamingEnumeration rowEnum = resultRow.getAttributes().getAll();
                String dn = resultRow.getNameInNamespace();
                qry.setAtEL("dn", len, dn);
                while (rowEnum.hasMore()) {
                    Attribute attr = (Attribute) rowEnum.next();
                    Collection.Key key = KeyImpl.init(attr.getID());
                    Enumeration values = attr.getAll();
                    Object value;
                    String existing, strValue;
                    while (values.hasMoreElements()) {
                        value = values.nextElement();
                        strValue = Caster.toString(value, null);
                        existing = Caster.toString(qry.getAt(key, len, null), null);
                        if (!StringUtil.isEmpty(existing) && !StringUtil.isEmpty(strValue)) {
                            value = existing + separator + strValue;
                        } else if (!StringUtil.isEmpty(existing))
                            value = existing;
                        qry.setAtEL(key, len, value);
                    }
                }
                if (maxrows > 0 && len >= maxrows)
                    break;
            }
        } else {
            outer: while (results.hasMoreElements()) {
                SearchResult resultRow = (SearchResult) results.next();
                if (row++ < startrow)
                    continue;
                Attributes attributesRow = resultRow.getAttributes();
                NamingEnumeration rowEnum = attributesRow.getIDs();
                while (rowEnum.hasMoreElements()) {
                    int len = qry.addRow();
                    String name = Caster.toString(rowEnum.next());
                    Object value = null;
                    try {
                        value = attributesRow.get(name).get();
                    } catch (Exception e) {
                    }
                    qry.setAtEL("name", len, name);
                    qry.setAtEL("value", len, value);
                    if (maxrows > 0 && len >= maxrows)
                        break outer;
                }
                qry.setAtEL("name", qry.size(), "dn");
            }
        }
    } finally {
        context.close();
    }
    // Sort
    if (sort != null && sort.length > 0) {
        int order = sortDirection == SORT_DIRECTION_ASC ? Query.ORDER_ASC : Query.ORDER_DESC;
        for (int i = sort.length - 1; i >= 0; i--) {
            String item = sort[i];
            if (item.indexOf(' ') != -1)
                item = ListUtil.first(item, " ", true);
            qry.sort(KeyImpl.getInstance(item), order);
        // keys[i] = new SortKey(item);
        }
    }
    return qry;
}
Also used : Enumeration(java.util.Enumeration) NamingEnumeration(javax.naming.NamingEnumeration) Query(lucee.runtime.type.Query) BasicAttribute(javax.naming.directory.BasicAttribute) Attribute(javax.naming.directory.Attribute) BasicAttributes(javax.naming.directory.BasicAttributes) Attributes(javax.naming.directory.Attributes) NamingEnumeration(javax.naming.NamingEnumeration) SearchResult(javax.naming.directory.SearchResult) ClassException(lucee.commons.lang.ClassException) NamingException(javax.naming.NamingException) PageException(lucee.runtime.exp.PageException) IOException(java.io.IOException) QueryImpl(lucee.runtime.type.QueryImpl) InitialLdapContext(javax.naming.ldap.InitialLdapContext) Collection(lucee.runtime.type.Collection) SearchControls(javax.naming.directory.SearchControls)

Example 34 with SearchControls

use of javax.naming.directory.SearchControls in project cas by apereo.

the class CasPersonDirectoryConfiguration method ldapAttributeRepositories.

@ConditionalOnMissingBean(name = "ldapAttributeRepositories")
@Bean
@RefreshScope
public List<IPersonAttributeDao> ldapAttributeRepositories() {
    final List<IPersonAttributeDao> list = new ArrayList<>();
    final PrincipalAttributesProperties attrs = casProperties.getAuthn().getAttributeRepository();
    attrs.getLdap().forEach(ldap -> {
        if (StringUtils.isNotBlank(ldap.getBaseDn()) && StringUtils.isNotBlank(ldap.getLdapUrl())) {
            final LdaptivePersonAttributeDao ldapDao = new LdaptivePersonAttributeDao();
            LOGGER.debug("Configured LDAP attribute source for [{}] and baseDn [{}]", ldap.getLdapUrl(), ldap.getBaseDn());
            ldapDao.setConnectionFactory(LdapUtils.newLdaptivePooledConnectionFactory(ldap));
            ldapDao.setBaseDN(ldap.getBaseDn());
            LOGGER.debug("LDAP attributes are fetched from [{}] via filter [{}]", ldap.getLdapUrl(), ldap.getSearchFilter());
            ldapDao.setSearchFilter(ldap.getSearchFilter());
            final SearchControls constraints = new SearchControls();
            if (ldap.getAttributes() != null && !ldap.getAttributes().isEmpty()) {
                LOGGER.debug("Configured result attribute mapping for [{}] to be [{}]", ldap.getLdapUrl(), ldap.getAttributes());
                ldapDao.setResultAttributeMapping(ldap.getAttributes());
                final String[] attributes = ldap.getAttributes().keySet().toArray(new String[ldap.getAttributes().keySet().size()]);
                constraints.setReturningAttributes(attributes);
            } else {
                LOGGER.debug("Retrieving all attributes as no explicit attribute mappings are defined for [{}]", ldap.getLdapUrl());
                constraints.setReturningAttributes(null);
            }
            if (ldap.isSubtreeSearch()) {
                LOGGER.debug("Configured subtree searching for [{}]", ldap.getLdapUrl());
                constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
            }
            constraints.setDerefLinkFlag(true);
            ldapDao.setSearchControls(constraints);
            ldapDao.setOrder(ldap.getOrder());
            LOGGER.debug("Initializing LDAP attribute source for [{}]", ldap.getLdapUrl());
            ldapDao.initialize();
            list.add(ldapDao);
        }
    });
    return list;
}
Also used : IPersonAttributeDao(org.apereo.services.persondir.IPersonAttributeDao) ArrayList(java.util.ArrayList) LdaptivePersonAttributeDao(org.apereo.services.persondir.support.ldap.LdaptivePersonAttributeDao) GrouperPrincipalAttributesProperties(org.apereo.cas.configuration.model.core.authentication.GrouperPrincipalAttributesProperties) PrincipalAttributesProperties(org.apereo.cas.configuration.model.core.authentication.PrincipalAttributesProperties) SearchControls(javax.naming.directory.SearchControls) RefreshScope(org.springframework.cloud.context.config.annotation.RefreshScope) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) Bean(org.springframework.context.annotation.Bean)

Example 35 with SearchControls

use of javax.naming.directory.SearchControls in project traccar by tananaev.

the class LdapProvider method isAdmin.

private boolean isAdmin(String accountName) {
    if (this.adminFilter != null) {
        try {
            InitialDirContext context = initContext();
            String searchString = adminFilter.replace(":login", accountName);
            SearchControls searchControls = new SearchControls();
            searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            NamingEnumeration<SearchResult> results = context.search(searchBase, searchString, searchControls);
            if (results.hasMoreElements()) {
                results.nextElement();
                if (results.hasMoreElements()) {
                    Log.warning("Matched multiple users for the accountName: " + accountName);
                    return false;
                }
                return true;
            }
        } catch (NamingException e) {
            return false;
        }
    }
    return false;
}
Also used : SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) InitialDirContext(javax.naming.directory.InitialDirContext)

Aggregations

SearchControls (javax.naming.directory.SearchControls)70 SearchResult (javax.naming.directory.SearchResult)55 NamingException (javax.naming.NamingException)35 ArrayList (java.util.ArrayList)24 NamingEnumeration (javax.naming.NamingEnumeration)21 Attributes (javax.naming.directory.Attributes)21 Attribute (javax.naming.directory.Attribute)19 DirContext (javax.naming.directory.DirContext)15 InitialDirContext (javax.naming.directory.InitialDirContext)14 IOException (java.io.IOException)8 LdapContext (javax.naming.ldap.LdapContext)8 HashMap (java.util.HashMap)5 GroupNotFoundException (org.jivesoftware.openfire.group.GroupNotFoundException)5 UserNotFoundException (org.jivesoftware.openfire.user.UserNotFoundException)5 HashSet (java.util.HashSet)4 LinkedHashSet (java.util.LinkedHashSet)4 Map (java.util.Map)4 PartialResultException (javax.naming.PartialResultException)4 Control (javax.naming.ldap.Control)4 LoginException (javax.security.auth.login.LoginException)4