Example usage for javax.naming.directory SearchControls SUBTREE_SCOPE

List of usage examples for javax.naming.directory SearchControls SUBTREE_SCOPE

Introduction

In this page you can find the example usage for javax.naming.directory SearchControls SUBTREE_SCOPE.

Prototype

int SUBTREE_SCOPE

To view the source code for javax.naming.directory SearchControls SUBTREE_SCOPE.

Click Source Link

Document

Search the entire subtree rooted at the named object.

Usage

From source file:org.cloudfoundry.identity.uaa.ldap.extension.SpringSecurityLdapTemplate.java

public SpringSecurityLdapTemplate(ContextSource contextSource) {
    Assert.notNull(contextSource, "ContextSource cannot be null");
    setContextSource(contextSource);//from  w w w .ja v  a 2 s  .c  o m

    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
}

From source file:ca.aedwards.ldap.compnent.LdapClConsumer.java

public List<LdapSearchResult> getAllPersonNames() {
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningObjFlag(true);/*www  . ja  v  a2s  . c o  m*/
    AndFilter filter = new AndFilter();
    //filter.and(new EqualsFilter("objectclass", "person"));
    filter.and(new GreaterThanOrEqualsFilter("changeNumber", Long.toString(clLast)));
    List<LdapSearchResult> results = endpoint.getLdapTemplate().search(DistinguishedName.EMPTY_PATH,
            filter.encode(), sc, new LdapResultContextMapper());
    //System.out.println("results: " + results.toString());
    System.out.println("Filter: " + filter.toString());
    return results;
}

From source file:org.ballerinalang.auth.ldap.util.LdapUtils.java

/**
 * Searches the corresponding name for a given username from LDAP.
 *
 * @param userName         Given username
 * @param searchBase       LDAP search base
 * @param searchFilter     LDAP search filter
 * @param dirContext Directory naming context
 * @return Associated name for the given username
 * @throws UserStoreException if there is any exception occurs during the process
 * @throws NamingException if there is any exception occurs during the process
 *//*from  ww w  . jav a2 s.c  om*/
public static String getNameInSpaceForUserName(String userName, String searchBase, String searchFilter,
        DirContext dirContext) throws UserStoreException, NamingException {

    if (userName == null) {
        throw new UserStoreException("userName value is null.");
    }
    String userDN = null;
    NamingEnumeration<SearchResult> answer = null;
    try {
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] searchBases = searchBase.split("#");
        for (String base : searchBases) {
            answer = dirContext.search(escapeDNForSearch(base), searchFilter, searchCtls);
            if (!(answer.hasMore())) {
                continue;
            }
            SearchResult userObj = answer.next();
            if (userObj != null) {
                //no need to decode since , if decoded the whole string, can't be encoded again
                //eg CN=Hello\,Ok=test\,test, OU=Industry
                userDN = userObj.getNameInNamespace();
                break;
            }
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Name in space for " + userName + " is " + userDN);
        }
    } finally {
        LdapUtils.closeNamingEnumeration(answer);
    }
    return userDN;
}

From source file:org.codehaus.plexus.redback.authentication.ldap.LdapBindAuthenticator.java

public AuthenticationResult authenticate(AuthenticationDataSource s) throws AuthenticationException {
    PasswordBasedAuthenticationDataSource source = (PasswordBasedAuthenticationDataSource) s;

    if (!config.getBoolean("ldap.bind.authenticator.enabled")
            || (!config.getBoolean("ldap.bind.authenticator.allowEmptyPasswords", false)
                    && StringUtils.isEmpty(source.getPassword()))) {
        return new AuthenticationResult(false, source.getPrincipal(), null);
    }/*from  ww  w  . j a  va2  s . com*/

    SearchControls ctls = new SearchControls();

    ctls.setCountLimit(1);

    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = "(&(objectClass=" + mapper.getUserObjectClass() + ")"
            + (mapper.getUserFilter() != null ? mapper.getUserFilter() : "") + "(" + mapper.getUserIdAttribute()
            + "=" + source.getPrincipal() + "))";

    log.info("Searching for users with filter: \'{}\'" + " from base dn: {}", filter, mapper.getUserBaseDn());

    LdapConnection ldapConnection = getLdapConnection();
    LdapConnection authLdapConnection = null;
    NamingEnumeration<SearchResult> results = null;
    try {
        // check the cache for user's userDn in the ldap server
        String userDn = ldapCacheService.getLdapUserDn(source.getPrincipal());

        if (userDn == null) {
            log.debug("userDn for user {} not found in cache. Retrieving from ldap server..",
                    source.getPrincipal());

            DirContext context = ldapConnection.getDirContext();

            results = context.search(mapper.getUserBaseDn(), filter, ctls);

            log.info("Found user?: {}", results.hasMoreElements());

            if (results.hasMoreElements()) {
                SearchResult result = results.nextElement();

                userDn = result.getNameInNamespace();

                log.debug("Adding userDn {} for user {} to the cache..", userDn, source.getPrincipal());

                // REDBACK-289/MRM-1488 cache the ldap user's userDn to lessen calls to ldap server
                ldapCacheService.addLdapUserDn(source.getPrincipal(), userDn);
            } else {
                return new AuthenticationResult(false, source.getPrincipal(), null);
            }
        }

        log.info("Attempting Authenication: + {}", userDn);

        authLdapConnection = connectionFactory.getConnection(userDn, source.getPassword());

        return new AuthenticationResult(true, source.getPrincipal(), null);
    } catch (LdapException e) {
        return new AuthenticationResult(false, source.getPrincipal(), e);
    } catch (NamingException e) {
        return new AuthenticationResult(false, source.getPrincipal(), e);
    } finally {
        closeNamingEnumeration(results);
        closeLdapConnection(ldapConnection);
        if (authLdapConnection != null) {
            closeLdapConnection(authLdapConnection);
        }
    }
}

From source file:com.jaeksoft.searchlib.util.ActiveDirectory.java

private NamingEnumeration<SearchResult> find(String filterExpr, String... returningAttributes)
        throws NamingException {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    if (returningAttributes == null || returningAttributes.length == 0)
        returningAttributes = DefaultReturningAttributes;
    searchControls.setReturningAttributes(returningAttributes);
    return dirContext.search(domainSearchName, filterExpr, searchControls);
}

From source file:it.infn.ct.security.utilities.LDAPUtils.java

public static LDAPUser findUserByMail(String mail) {
    NamingEnumeration results = null;
    DirContext ctx = null;/*w w w.  j  ava 2  s .co m*/
    LDAPUser user = null;
    try {
        ctx = getContext();
        SearchControls controls = new SearchControls();
        String retAttrs[] = { "cn" };
        controls.setReturningAttributes(retAttrs);
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ResourceBundle rb = ResourceBundle.getBundle("ldap");

        results = ctx.search(rb.getString("peopleRoot"), "(mail=" + mail + ")", controls);
        if (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            Attributes attributes = searchResult.getAttributes();
            user = new LDAPUser();

            if (attributes.get("cn") != null)
                user = getUser((String) attributes.get("cn").get());
        }
    } catch (NameNotFoundException ex) {
        _log.error(ex);
    } catch (NamingException e) {
        _log.error(e);
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }
    return user;

}

From source file:org.apache.cxf.sts.claims.LdapUtils.java

public static List<String> getAttributeOfEntries(LdapTemplate ldapTemplate, String baseDN, String objectClass,
        String filterAttributeName, String filterAttributeValue, String searchAttribute) {

    List<String> ldapAttributes = null;

    AttributesMapper mapper = new AttributesMapper() {
        public Object mapFromAttributes(Attributes attrs) throws NamingException {
            NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
            while (attrEnum.hasMore()) {
                return (String) attrEnum.next().get();
            }//w  ww .j av a  2  s .c  o m
            return null;
        }
    };

    String[] searchAttributes = new String[] { searchAttribute };

    List<?> result = null;
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectclass", objectClass))
            .and(new EqualsFilter(filterAttributeName, filterAttributeValue));

    result = ldapTemplate.search((baseDN == null) ? "" : baseDN, filter.toString(),
            SearchControls.SUBTREE_SCOPE, searchAttributes, mapper);
    if (result != null && result.size() > 0) {
        ldapAttributes = CastUtils.cast((List<?>) result);
    }

    return ldapAttributes;
}

From source file:com.swdouglass.joid.server.DirectoryUserManagerImpl.java

private Attributes findAttributes(String inUsername, InitialDirContext ctx) throws NamingException {

    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    // perform the search
    NamingEnumeration results = ctx.search("", "(uid={0})", new Object[] { inUsername }, ctls);

    Attributes outAttrs = null;//  ww w  .j  a  va 2  s  . c o  m
    if (results.hasMore()) {
        log.info("Found username \"" + inUsername + "\" in directory");
        outAttrs = ((SearchResult) results.next()).getAttributes();
    } else {
        log.info("Could NOT find username \"" + inUsername + "\" in directory");
    }
    return outAttrs;
}

From source file:io.lavagna.service.Ldap.java

public Pair<Boolean, List<String>> authenticateWithParams(String providerUrl, String ldapManagerDn,
        String ldapManagerPwd, String base, String filter, String username, String password) {
    requireNonNull(username);//from w  ww  .j a  v  a 2 s.c om
    requireNonNull(password);
    List<String> msgs = new ArrayList<>();

    msgs.add(format("connecting to %s with managerDn %s", providerUrl, ldapManagerDn));
    try (InitialDirContextCloseable dctx = ldapConnection.context(providerUrl, ldapManagerDn, ldapManagerPwd)) {
        msgs.add(format("connected [ok]"));
        msgs.add(format("now searching user \"%s\" with base %s and filter %s", username, base, filter));

        SearchControls sc = new SearchControls();
        sc.setReturningAttributes(null);
        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

        List<SearchResult> srs = Ldap.search(dctx, base,
                new MessageFormat(filter).format(new Object[] { Ldap.escapeLDAPSearchFilter(username) }), sc);
        if (srs.size() != 1) {
            String msg = format("error for username \"%s\" we have %d results instead of 1 [error]", username,
                    srs.size());
            msgs.add(msg);
            LOG.info(msg, username, srs.size());
            return Pair.Companion.of(false, msgs);
        }

        msgs.add("user found, now will connect with given password [ok]");

        SearchResult sr = srs.get(0);

        try (InitialDirContextCloseable uctx = ldapConnection.context(providerUrl, sr.getNameInNamespace(),
                password)) {
            msgs.add("user authenticated, everything seems ok [ok]");
            return Pair.Companion.of(true, msgs);
        } catch (NamingException e) {
            String msg = format("error while checking with username \"%s\" with message: %s [error]", username,
                    e.getMessage());
            msgs.add(msg);
            LOG.info(msg, e);
            return Pair.Companion.of(false, msgs);
        }
    } catch (Throwable e) {
        String errMsg = format(
                "error while opening the connection with message: %s [error], check the logs for a more complete trace",
                e.getMessage());
        msgs.add(errMsg);
        msgs.add("Full stacktrace is:");
        msgs.add(ExceptionUtils.getStackTrace(e));
        LOG.error(errMsg, e);
        return Pair.Companion.of(false, msgs);
    }
}

From source file:com.adito.activedirectory.PagedResultTemplate.java

private void doSearch(InitialLdapContext context, String filter, String[] attributes, PagedResultMapper mapper)
        throws NamingException {
    SearchControls constraints = new SearchControls();
    constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);

    for (String searchBase : ouSearchBase) {
        if (logger.isDebugEnabled()) {
            logger.debug("Looking for items starting at " + searchBase + " (filter = " + filter + ")");
        }/*w  w w .j a v a  2  s .co m*/

        try {
            constraints.setReturningAttributes(attributes);
            NamingEnumeration<SearchResult> results = context.search(searchBase, filter, constraints);
            mapResults(mapper, results);
        } catch (PartialResultException e) {
            // ignore
        } catch (NamingException e) {
            mapper.processException(e);
            logger.error("Possible configuration error! Did you enter your OUs correctly? [" + searchBase + "]",
                    e);
        }
    }
}