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:ldap.SearchUtility.java

public boolean checkPassword(String DN, String pwdAtt, String value, DirContext context)
        throws NamingException, UnsupportedEncodingException {
    SearchControls ctls = new SearchControls();
    ctls.setReturningAttributes(new String[0]); // Return no attrs
    ctls.setSearchScope(SearchControls.OBJECT_SCOPE); // Search object only
    //byte[] pwdBytes = value.getBytes("UTF-8");
    byte[] pwdBytes = value.getBytes(LdapConstants.UTF8);

    // Invoke search method that will use the LDAP "compare" operation
    NamingEnumeration answer = context.search(DN, "(" + pwdAtt + "={0})", new Object[] { pwdBytes }, ctls);
    return answer.hasMore();
}

From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java

/**
 * Performs a search of LDAP//from   w ww.j a  va 2 s .c  om
 * 
 * @param username
 *            The username to be used in the search
 * @param dc
 *            The directory context to use for the search
 * @return An enumeration containing the search results
 * @throws NamingException
 */
private NamingEnumeration<SearchResult> performLdapSearch(String username, DirContext dc)
        throws NamingException {
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = "(" + filterPrefix + idAttr + "=" + username + filterSuffix + ")";

    NamingEnumeration<SearchResult> ne = dc.search(baseDn, filter, sc);
    log.trace(String.format("performing LDAP search using baseDn: %s, filter: %s", baseDn, filter));
    return ne;
}

From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java

private String performRoleSearch(String location, String roleName) {
    String val = null;
    try {/*from   ww w  . j  a  v a  2 s  . c  om*/

        DirContext dc = new InitialDirContext(env);
        SearchControls sc = new SearchControls();
        sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);

        //String filter = "(" + filterPrefix + roleName + ")";
        NamingEnumeration<SearchResult> ne = dc.search(location, roleName, sc);
        if (ne.hasMore()) {
            val = getAttrValue("memberOf", ne.next());
        }
        ne.close();
        dc.close();
    } catch (NamingException ne) {
        log.warn("Failed LDAP lookup getAttr", ne);
        log.warn("roleName:", roleName);
        log.warn("location:", location);
    }
    return val;

}

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

private SearchControls getSearchControls(final String[] attributeIds) {
    final SearchControls constraints = new SearchControls();

    constraints.setSearchScope(this.scope);
    constraints.setReturningAttributes(attributeIds);
    constraints.setTimeLimit(this.timeout);
    constraints.setCountLimit(this.maxNumberResults);

    return constraints;
}

From source file:org.archone.ad.domain.LdapActions.java

@RPCAction(name = "group.list", required = { "domain" })
@SecuredMethod(constraints = "administrator.by_domain")
public HashMap<String, Object> listGroups(OperationContext opContext) throws NamingException {

    String domain = (String) opContext.getParams().get("domain");

    DirContextAdapter userDirContext = (DirContextAdapter) SecurityUtils.getSubject().getPrincipal();

    DomainDn domainDn = nameHelper.newDomainDnFromDomain(domain);

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

    NamingEnumeration<SearchResult> searchResults = userDirContext.search(nameHelper.getGroupsBaseDn(domainDn),
            "(cn=*)", controls);

    List<HashMap<String, Object>> groups = new LinkedList<HashMap<String, Object>>();
    while (searchResults.hasMore()) {
        SearchResult sr = searchResults.next();
        if (nameHelper.isGroupDn(sr.getNameInNamespace().toLowerCase())) {
            HashMap<String, Object> group = new HashMap<String, Object>();
            group.put("groupId", nameHelper.newGroupDn(sr.getNameInNamespace().toLowerCase()).getAsGroupId());
            groups.add(group);//from  w  w w  .java2s . c om
        }
    }

    HashMap<String, Object> response = new HashMap<String, Object>();
    response.put("groups", groups);

    return response;
}

From source file:org.archone.ad.domain.LdapActions.java

@RPCAction(name = "user.membership.get", required = { "userId" })
@SecuredMethod(constraints = "administrator.by_domain")
public HashMap<String, Object> listMermbershipGroups(OperationContext opContext) throws NamingException {

    String userId = (String) opContext.getParams().get("userId");

    UserDn userDn = nameHelper.newUserDnFromId(userId);
    DomainDn domainDn = nameHelper.newDomainDnFromDomain(userDn.getDomain());

    DirContextAdapter userDirContext = (DirContextAdapter) SecurityUtils.getSubject().getPrincipal();

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

    NamingEnumeration<SearchResult> searchResults = userDirContext.search(
            nameHelper.getGroupsBaseDn(nameHelper.newDomainDnFromDomain(userDn.getDomain())),
            "(uniqueMember=" + userDn.toString() + ")", controls);

    List<HashMap<String, Object>> groups = new LinkedList<HashMap<String, Object>>();
    while (searchResults.hasMore()) {
        SearchResult sr = searchResults.next();
        if (nameHelper.isGroupDn(sr.getNameInNamespace().toLowerCase())) {
            HashMap<String, Object> group = new HashMap<String, Object>();
            group.put("groupId", nameHelper.newGroupDn(sr.getNameInNamespace().toLowerCase()).getAsGroupId());
            groups.add(group);/*from  w w w  . j  a v a  2  s.c  om*/
        }
    }

    HashMap<String, Object> response = new HashMap<String, Object>();
    response.put("groups", groups);

    return response;
}

From source file:org.archone.ad.domain.LdapActions.java

@RPCAction(name = "user.remove", required = { "userId" })
@SecuredMethod(constraints = "administrator.by_domain")
public HashMap<String, Object> removeUser(OperationContext opContext) throws NamingException {

    String userId = (String) opContext.getParams().get("userId");

    DirContextAdapter userDirContext = (DirContextAdapter) SecurityUtils.getSubject().getPrincipal();

    UserDn userDn = nameHelper.newUserDnFromId(userId);

    DomainDn domainDn = nameHelper.newDomainDnFromDomain(userDn.getDomain());

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

    NamingEnumeration<SearchResult> searchResults = userDirContext.search(
            nameHelper.getGroupsBaseDn(nameHelper.newDomainDnFromDomain(userDn.getDomain())),
            "(uniqueMember=" + userDn.toString() + ")", controls);

    while (searchResults.hasMore()) {
        SearchResult sr = searchResults.next();
        DirContextAdapter dca = (DirContextAdapter) userDirContext.lookup(sr.getNameInNamespace());
        dca.removeAttributeValue("uniqueMember", userDn.toString());
        userDirContext.modifyAttributes(sr.getNameInNamespace(), dca.getModificationItems());
    }//from w  w  w . j  a  v  a2 s. c om

    userDirContext.unbind(userDn);

    HashMap<String, Object> response = new HashMap<String, Object>();
    response.put("success", true);

    return response;
}

From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java

private boolean bindSearchX(String username, String password, Hashtable<String, String> env, boolean bind)
        throws AuthenticationException, NamingException {

    env.put(Context.SECURITY_PRINCIPAL, ldapSecurityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, ldapSecurityCredentials);

    DirContext ctx = null;/*w  ww. ja v  a  2s .c  o  m*/
    try {
        ctx = new InitialDirContext(env);
    } catch (NamingException ne) {
        log.error("Failed to bind as: {}", ldapSecurityPrincipal);
    }

    // ensure we have the userPassword attribute at a minimum
    String[] attributeList = new String[] { "userPassword" };

    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(attributeList);
    sc.setDerefLinkFlag(true);
    sc.setReturningObjFlag(false);
    sc.setTimeLimit(5000);

    String filter = "(" + filterPrefix + idAttr + "=" + username + filterSuffix + ")";
    // Do the search
    NamingEnumeration<SearchResult> results = ctx.search(baseDn, filter, sc);
    if (!results.hasMore()) {
        log.warn("no valid user found.");
        return false;
    }

    SearchResult result = results.next();
    log.debug("authenticating user: {}", result.getNameInNamespace());

    if (bind) {
        // setup user context for binding
        Hashtable<String, String> userEnv = new Hashtable<String, String>();
        userEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        userEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
        userEnv.put(Context.PROVIDER_URL, baseUrl);
        userEnv.put(Context.SECURITY_PRINCIPAL, result.getNameInNamespace());
        userEnv.put(Context.SECURITY_CREDENTIALS, password);

        try {
            new InitialDirContext(userEnv);
        } catch (NamingException ne) {
            log.error("failed to authenticate user: " + result.getNameInNamespace());
            throw ne;
        }
    } else {
        // get userPassword attribute
        Attribute up = result.getAttributes().get("userPassword");
        if (up == null) {
            log.error("unable to read userPassword attribute for: {}", result.getNameInNamespace());
            return false;
        }

        byte[] userPasswordBytes = (byte[]) up.get();
        String userPassword = new String(userPasswordBytes);

        // compare passwords - also handles encodings
        if (!passwordsMatch(password, userPassword)) {
            return false;
        }
    }

    return true;
}

From source file:com.aurel.track.util.LdapUtil.java

/**
 * Returns a HashMap <login name, TPersonBean> for all LDAP objects found in
 * the directory und the DN configured in the Genji server configuration.
 * // www.j  av  a 2s  .  co m
 * @return Map with <login name, TPersonBean>
 */
public static HashMap<String, TPersonBean> getAllLdapPersonsPaged(TSiteBean siteBean, String filter)
        throws Exception {
    if (filter == null || "".equals(filter) || "*".equals(filter)) {
        filter = siteBean.getLdapAttributeLoginName() + "=*";
    }
    if (!(filter.startsWith("(") && filter.endsWith(")"))) {
        filter = "(" + filter + ")";
    }
    LOGGER.debug("User filter expression " + filter);
    String bindDN = siteBean.getLdapBindDN();
    String bindPassword = siteBean.getLdapBindPassword();
    HashMap<String, TPersonBean> ldapPersonsMap = new HashMap<String, TPersonBean>();
    LdapContext context = getInitialContext(siteBean.getLdapServerURL(), bindDN, bindPassword);
    if (context == null) {
        return ldapPersonsMap;
    }
    int recordCount = 0;
    // Create initial context
    // Control the search
    SearchControls ctls = null;
    try {
        // Activate paged results
        int pageSize = 5;
        byte[] cookie = null;
        context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
        int total;
        // Control the search
        ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers()
                + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // Don't ask for more than we can handle
                                                                                                                                                                     // anyways
        if (ldapMap == null || ldapMap.isEmpty()) {
            LOGGER.error("There is no LDAP mapping in quartz-jobs.xml. Please provide!");
            return null;
        }
        String firstNameAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.FIRST_NAME);
        String lastNameAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.LAST_NAME);
        String emailAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.EMAIL);
        String phoneAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.PHONE);
        String loginAttributeName = siteBean.getLdapAttributeLoginName();
        do {
            /* perform the search */
            NamingEnumeration<SearchResult> results = context.search("", filter, ctls);
            /* for each entry print out name + all attrs and values */
            while (results != null && results.hasMore()) {
                SearchResult sr = (SearchResult) results.next();
                // Attributes atrs = sr.getAttributes();
                TPersonBean personBean = getPersonBean(sr, loginAttributeName, firstNameAttributeName,
                        lastNameAttributName, emailAttributeName, phoneAttributName);
                if (personBean != null) {
                    ldapPersonsMap.put(personBean.getLoginName(), personBean);
                }
                ++recordCount;
            }
            // Examine the paged results control response
            Control[] controls = context.getResponseControls();
            if (controls != null) {
                for (int i = 0; i < controls.length; i++) {
                    if (controls[i] instanceof PagedResultsResponseControl) {
                        PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                        total = prrc.getResultSize();
                        if (total != 0) {
                            LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total
                                    + ") *****************\n");
                        } else {
                            LOGGER.debug(
                                    "***************** END-OF-PAGE " + "(total: unknown) ***************\n");
                        }
                        cookie = prrc.getCookie();
                    }
                }
            } else {
                LOGGER.debug("No controls were sent from the server");
            }
            // Re-activate paged results
            context.setRequestControls(
                    new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });

        } while (cookie != null);
    } catch (SizeLimitExceededException sle) {
        if (recordCount < ctls.getCountLimit()) {
            LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server.");
            LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with "
                    + sle.getMessage());
            LOGGER.error(
                    "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter.");
        } else {
            LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server ("
                    + recordCount + ").");
            LOGGER.error(
                    "You have to get more user licenses for Genji or specify a more suitable search base or filter.");
        }
        LOGGER.error("The LDAP synchronization is most likely incomplete.");
    } catch (NamingException e) {
        LOGGER.error("PagedSearch failed.");
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    } catch (IOException ie) {
        LOGGER.error("PagedSearch failed.");
        LOGGER.debug(ExceptionUtils.getStackTrace(ie));
    } finally {
        if (context != null) {
            context.close();
        }
    }
    return ldapPersonsMap;
}