Example usage for javax.naming.directory SearchControls setSearchScope

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

Introduction

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

Prototype

public void setSearchScope(int scope) 

Source Link

Document

Sets the search scope to one of: OBJECT_SCOPE, ONELEVEL_SCOPE, SUBTREE_SCOPE.

Usage

From source file:org.jasig.cas.adaptors.ldap.BindLdapAuthenticationHandler.java

private SearchControls getSearchControls() {
    final SearchControls constraints = new SearchControls();
    constraints.setSearchScope(this.scope);
    constraints.setReturningAttributes(new String[0]);
    constraints.setTimeLimit(this.timeout);
    constraints.setCountLimit(this.maxNumberResults);

    return constraints;
}

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  w  w . ja v a2s .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.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:fi.koku.services.utility.authorization.impl.GroupServiceLDAPImpl.java

private List<LdapPerson> getPersonDnsByPics(List<String> pics) {
    SearchControls ctrl = new SearchControls();
    ctrl.setReturningAttributes(new String[] { "uid" });
    ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String q = getPersonsQuery(pics);
    logger.debug("getPersonDnsByPics: query: " + q.toString());
    List<LdapPerson> persons = ldapTemplate.search("", q, ctrl, new LdapPersonMapper(),
            new DirContextProcessorNoop());
    logger.debug("persons: " + persons.size());
    return persons;
}

From source file:jp.ikedam.jenkins.plugins.ldap_sasl.SearchUserDnResolver.java

/**
 * Resolve the user DN by querying the LDAP directory.
 * //ww  w . j  a va2s . co m
 * @param ctx LDAP context, already authenticated.
 * @param username the username the user authenticated with.
 * 
 * @return the DN of the user.
 * @see jp.ikedam.jenkins.plugins.ldap_sasl.UserDnResolver#getUserDn(javax.naming.ldap.LdapContext, java.lang.String)
 */
@Override
public String getUserDn(LdapContext ctx, String username) {
    Logger logger = getLogger();
    if (StringUtils.isBlank(getSearchQueryTemplate())) {
        // not configured.
        logger.severe("Not configured.");

        return null;
    }

    try {
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        logger.fine(String.format("Searching users base=%s, username=%s", getSearchBase(), username));
        String query = expandUsername(getSearchQueryTemplate(), username);
        NamingEnumeration<SearchResult> entries = ctx.search((getSearchBase() != null) ? getSearchBase() : "",
                query, searchControls);
        if (!entries.hasMore()) {
            // no entry.
            logger.severe(String.format("User not found: %s", username));
            return null;
        }

        String userDn = entries.next().getNameInNamespace();

        if (entries.hasMore()) {
            // more than one entry.
            logger.severe(String.format("User found more than one: %s", username));
            return null;
        }
        entries.close();

        return userDn;
    } catch (NamingException e) {
        logger.log(Level.SEVERE, "Failed to search a user", e);
        return null;
    }
}

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

private void doPagedSearch(InitialLdapContext context, String filter, String[] attributes,
        PagedResultMapper mapper) throws NamingException {
    SearchControls constraints = new SearchControls();
    constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
    applyControls(context, pageSize);//ww  w.  ja  v a 2  s.  co  m

    for (String searchBase : ouSearchBase) {
        if (logger.isDebugEnabled()) {
            logger.debug("Looking for items starting at " + searchBase + " (filter = " + filter + ")");
        }

        try {
            int currentPage = 1;
            int startPosition = 0;
            int endPosition = pageSize - 1;
            byte[] cookie = null;

            do {
                String range = startPosition + "-" + endPosition;

                if (logger.isDebugEnabled()) {
                    logger.debug("Starting search on page " + currentPage + " " + range);
                }

                constraints.setReturningAttributes(attributes);
                NamingEnumeration<SearchResult> results = context.search(searchBase, filter, constraints);

                try {
                    mapResults(mapper, results);
                } catch (PartialResultException pre) {
                    // We're paging so we dont care and don't log anymore
                }

                // Examine the paged results control response
                Control[] controls = context.getResponseControls();
                if (controls != null) {
                    for (int index = 0; index < controls.length; index++) {
                        if (controls[index] instanceof PagedResultsResponseControl) {
                            PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[index];
                            cookie = prrc.getCookie();
                        }
                    }
                }

                applyControls(context, pageSize, cookie);
                startPosition = startPosition + pageSize;
                endPosition = endPosition + pageSize;
                currentPage++;
            } while ((cookie != null) && (cookie.length != 0));
        } catch (NamingException e) {
            mapper.processException(e);
            logger.error("Possible configuration error! Did you enter your OUs correctly? [" + searchBase + "]",
                    e);
        }
    }
}

From source file:com.teklabs.throng.integration.ldap.Ldap.java

private String getPrincipal(String login) throws NamingException {
    if (baseDN == null) {
        throw new IllegalArgumentException("LDAP BaseDN is not set");
    }//w w  w  . java 2  s  .c  o m
    InitialDirContext context = null;
    String principal;
    try {
        if (LdapHelper.LOG.isDebugEnabled()) {
            LdapHelper.LOG.debug("Search principal: " + login);
        }

        context = ldapContextFactory.getInitialDirContext();
        String request = "(&(objectClass=" + userObjectClass + ")(" + loginAttribute + "={0}))";
        if (LdapHelper.LOG.isDebugEnabled()) {
            LdapHelper.LOG.debug("LDAP request: " + request);
        }

        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        controls.setReturningAttributes(new String[] {});
        controls.setReturningObjFlag(true);
        NamingEnumeration result = context.search(baseDN, request, new String[] { login }, controls);
        String found = null;
        if (result.hasMore()) {
            SearchResult obj = (SearchResult) result.next();
            found = obj.getNameInNamespace();
            if (found != null && result.hasMore()) {
                found = null;
                LdapHelper.LOG.error(
                        "Login \'" + login + "\' is not unique in LDAP (see attribute " + loginAttribute + ")");
            }
        }

        principal = found;
    } finally {
        LdapHelper.closeContext(context);
    }

    return principal;
}

From source file:eu.uqasar.util.ldap.LdapManager.java

private SearchControls getDefaultSearchControls() {
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SUBTREE_SCOPE);
    controls.setReturningAttributes(null);
    controls.setReturningObjFlag(true);//w  ww. jav  a 2s . c  o m
    return controls;
}

From source file:org.jasig.portlet.contacts.adapters.impl.ldap.LdapSearchAdapter.java

/**
 * Construct a new search controls object for our search
 *//*from   w w  w  .  j  a v a2  s .c  om*/
protected SearchControls getSearchControls() {
    SearchControls searchControls = new SearchControls();
    searchControls.setTimeLimit(timeLimit);
    searchControls.setCountLimit(countLimit);
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    return searchControls;
}

From source file:net.identio.server.service.authentication.ldap.LdapAuthenticationProvider.java

public AuthenticationResult validate(AuthMethod authMethod, Authentication authentication,
        TransactionData transactionData) {

    LdapAuthMethod ldapAuthMethod = (LdapAuthMethod) authMethod;
    UserPasswordAuthentication userPwAuthentication = (UserPasswordAuthentication) authentication;

    boolean validation;

    String userId = userPwAuthentication.getUserId();
    String password = userPwAuthentication.getPassword();

    GenericObjectPool<InitialLdapContext> pool = pools.get(authMethod.getName());

    InitialLdapContext ctx = null;

    try {//from w  w  w  .j  av  a 2s  .  co m
        ctx = pool.borrowObject();

        // First we search the user
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String searchFilter = ldapAuthMethod.getUserSearchFilter().replace("#UID",
                SecurityUtils.escapeLDAPSearchFilter(userId));

        NamingEnumeration<SearchResult> results = ctx.search(ldapAuthMethod.getBaseDn(), searchFilter,
                controls);

        SearchResult result;

        if (results.hasMoreElements()) {
            result = results.next();

            if (results.hasMoreElements()) {
                LOG.error("User ID {} is not unique in LDAP {}", userId, authMethod.getName());
                return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL)
                        .setErrorStatus(AuthenticationErrorStatus.USER_NOT_UNIQUE);
            }
        } else {
            LOG.error("User ID {} does not exist in LDAP {}", userId, authMethod.getName());
            return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL)
                    .setErrorStatus(AuthenticationErrorStatus.INVALID_CREDENTIALS);
        }

        // Try to bind with the found user id
        validation = ((LdapConnectionFactory) pool.getFactory()).authenticate(authMethod.getName(),
                result.getNameInNamespace(), password);

        pool.returnObject(ctx);

        if (validation) {
            LOG.info("User {} successfully authenticated with {}", userId, authMethod.getName());
            return new AuthenticationResult().setStatus(AuthenticationResultStatus.SUCCESS).setUserId(userId)
                    .setAuthMethod(authMethod).setAuthLevel(authMethod.getAuthLevel());
        } else {
            LOG.error("Authentication failed for user {} with {}", userId, authMethod.getName());
            return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL)
                    .setErrorStatus(AuthenticationErrorStatus.INVALID_CREDENTIALS);
        }

    } catch (Exception ex) {

        // Discard context
        try {
            if (ctx != null) {
                pool.invalidateObject(ctx);
            }
        } catch (Exception ex2) {
            LOG.error("An error occurend when authenticating user");
        }

        return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL)
                .setErrorStatus(AuthenticationErrorStatus.TECHNICAL_ERROR);
    }

}