Search in sources :

Example 6 with SearchControls

use of javax.naming.directory.SearchControls in project jetty.project by eclipse.

the class LdapLoginModule method getUserRolesByDn.

private List<String> getUserRolesByDn(DirContext dirContext, String userDn) throws LoginException, NamingException {
    List<String> roleList = new ArrayList<String>();
    if (dirContext == null || _roleBaseDn == null || _roleMemberAttribute == null || _roleObjectClass == null) {
        return roleList;
    }
    SearchControls ctls = new SearchControls();
    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setReturningAttributes(new String[] { _roleNameAttribute });
    String filter = "(&(objectClass={0})({1}={2}))";
    Object[] filterArguments = { _roleObjectClass, _roleMemberAttribute, userDn };
    NamingEnumeration<SearchResult> results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls);
    LOG.debug("Found user roles?: " + results.hasMoreElements());
    while (results.hasMoreElements()) {
        SearchResult result = (SearchResult) results.nextElement();
        Attributes attributes = result.getAttributes();
        if (attributes == null) {
            continue;
        }
        Attribute roleAttribute = attributes.get(_roleNameAttribute);
        if (roleAttribute == null) {
            continue;
        }
        NamingEnumeration<?> roles = roleAttribute.getAll();
        while (roles.hasMore()) {
            roleList.add(roles.next().toString());
        }
    }
    return roleList;
}
Also used : Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) Attributes(javax.naming.directory.Attributes) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult)

Example 7 with SearchControls

use of javax.naming.directory.SearchControls in project Openfire by igniterealtime.

the class LdapManager method retrieveList.

/**
     * Generic routine for retrieving a list of results from the LDAP server.  It's meant to be very
     * flexible so that just about any query for a list of results can make use of it without having
     * to reimplement their own calls to LDAP.  This routine also accounts for sorting settings,
     * paging settings, any other global settings, and alternate DNs.
     *
     * The passed in filter string needs to be pre-prepared!  In other words, nothing will be changed
     * in the string before it is used as a string.
     *
     * @param attribute LDAP attribute to be pulled from each result and placed in the return results.
     *     Typically pulled from this manager.
     * @param searchFilter Filter to use to perform the search.  Typically pulled from this manager.
     * @param startIndex Number/index of first result to include in results.  (-1 for no limit)
     * @param numResults Number of results to include.  (-1 for no limit)
     * @param suffixToTrim An arbitrary string to trim from the end of every attribute returned.  null to disable.
     * @param escapeJIDs Use JID-escaping for returned results (e.g. usernames)
     * @return A simple list of strings (that should be sorted) of the results.
     */
public List<String> retrieveList(String attribute, String searchFilter, int startIndex, int numResults, String suffixToTrim, boolean escapeJIDs) {
    List<String> results = new ArrayList<>();
    int pageSize = -1;
    String pageSizeStr = properties.get("ldap.pagedResultsSize");
    if (pageSizeStr != null) {
        try {
            pageSize = Integer.parseInt(pageSizeStr);
        /* radix -1 is invalid */
        } catch (NumberFormatException e) {
        // poorly formatted number, ignoring
        }
    }
    Boolean clientSideSort = false;
    String clientSideSortStr = properties.get("ldap.clientSideSorting");
    if (clientSideSortStr != null) {
        clientSideSort = Boolean.valueOf(clientSideSortStr);
    }
    LdapContext ctx = null;
    LdapContext ctx2 = null;
    try {
        ctx = getContext(baseDN);
        // Set up request controls, if appropriate.
        List<Control> baseTmpRequestControls = new ArrayList<>();
        if (!clientSideSort) {
            // Server side sort on username field.
            baseTmpRequestControls.add(new SortControl(new String[] { attribute }, Control.NONCRITICAL));
        }
        if (pageSize > 0) {
            // Server side paging.
            baseTmpRequestControls.add(new PagedResultsControl(pageSize, Control.NONCRITICAL));
        }
        Control[] baseRequestControls = baseTmpRequestControls.toArray(new Control[baseTmpRequestControls.size()]);
        ctx.setRequestControls(baseRequestControls);
        SearchControls searchControls = new SearchControls();
        // See if recursive searching is enabled. Otherwise, only search one level.
        if (isSubTreeSearch()) {
            searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        } else {
            searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        }
        searchControls.setReturningAttributes(new String[] { attribute });
        // If server side sort, we'll skip the initial ones we don't want, and stop when we've hit
        // the amount we do want.
        int skip = -1;
        int lastRes = -1;
        if (!clientSideSort) {
            if (startIndex != -1) {
                skip = startIndex;
            }
            if (numResults != -1) {
                lastRes = startIndex + numResults;
            }
        }
        byte[] cookie;
        int count = 0;
        // Run through all pages of results (one page is also possible  ;)  )
        do {
            cookie = null;
            NamingEnumeration<SearchResult> answer = ctx.search("", searchFilter, searchControls);
            // Examine all of the results on this page
            while (answer.hasMoreElements()) {
                count++;
                if (skip > 0 && count <= skip) {
                    answer.next();
                    continue;
                }
                if (lastRes != -1 && count > lastRes) {
                    answer.next();
                    break;
                }
                // Get the next result.
                String result = (String) answer.next().getAttributes().get(attribute).get();
                // Remove suffixToTrim if set
                if (suffixToTrim != null && suffixToTrim.length() > 0 && result.endsWith(suffixToTrim)) {
                    result = result.substring(0, result.length() - suffixToTrim.length());
                }
                // Add this to the result.
                results.add(escapeJIDs ? JID.escapeNode(result) : result);
            }
            // Examine the paged results control response
            Control[] controls = ctx.getResponseControls();
            if (controls != null) {
                for (Control control : controls) {
                    if (control instanceof PagedResultsResponseControl) {
                        PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
                        cookie = prrc.getCookie();
                    }
                }
            }
            // Close the enumeration.
            answer.close();
            // Re-activate paged results; affects nothing if no paging support
            List<Control> tmpRequestControls = new ArrayList<>();
            if (!clientSideSort) {
                // Server side sort on username field.
                tmpRequestControls.add(new SortControl(new String[] { attribute }, Control.NONCRITICAL));
            }
            if (pageSize > 0) {
                // Server side paging.
                tmpRequestControls.add(new PagedResultsControl(pageSize, cookie, Control.CRITICAL));
            }
            Control[] requestControls = tmpRequestControls.toArray(new Control[tmpRequestControls.size()]);
            ctx.setRequestControls(requestControls);
        } while (cookie != null && (lastRes == -1 || count <= lastRes));
        // Add groups found in alternate DN
        if (alternateBaseDN != null && (lastRes == -1 || count <= lastRes)) {
            ctx2 = getContext(alternateBaseDN);
            ctx2.setRequestControls(baseRequestControls);
            // Run through all pages of results (one page is also possible  ;)  )
            do {
                cookie = null;
                NamingEnumeration<SearchResult> answer = ctx2.search("", searchFilter, searchControls);
                // Examine all of the results on this page
                while (answer.hasMoreElements()) {
                    count++;
                    if (skip > 0 && count <= skip) {
                        answer.next();
                        continue;
                    }
                    if (lastRes != -1 && count > lastRes) {
                        answer.next();
                        break;
                    }
                    // Get the next result.
                    String result = (String) answer.next().getAttributes().get(attribute).get();
                    // Remove suffixToTrim if set
                    if (suffixToTrim != null && suffixToTrim.length() > 0 && result.endsWith(suffixToTrim)) {
                        result = result.substring(0, result.length() - suffixToTrim.length());
                    }
                    // Add this to the result.
                    results.add(escapeJIDs ? JID.escapeNode(result) : result);
                }
                // Examine the paged results control response
                Control[] controls = ctx2.getResponseControls();
                if (controls != null) {
                    for (Control control : controls) {
                        if (control instanceof PagedResultsResponseControl) {
                            PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
                            cookie = prrc.getCookie();
                        }
                    }
                }
                // Close the enumeration.
                answer.close();
                // Re-activate paged results; affects nothing if no paging support
                List<Control> tmpRequestControls = new ArrayList<>();
                if (!clientSideSort) {
                    // Server side sort on username field.
                    tmpRequestControls.add(new SortControl(new String[] { attribute }, Control.NONCRITICAL));
                }
                if (pageSize > 0) {
                    // Server side paging.
                    tmpRequestControls.add(new PagedResultsControl(pageSize, cookie, Control.CRITICAL));
                }
                Control[] requestControls = tmpRequestControls.toArray(new Control[tmpRequestControls.size()]);
                ctx2.setRequestControls(requestControls);
            } while (cookie != null && (lastRes == -1 || count <= lastRes));
        }
        // If client-side sorting is enabled, sort and trim.
        if (clientSideSort) {
            Collections.sort(results);
            if (startIndex != -1 || numResults != -1) {
                if (startIndex == -1) {
                    startIndex = 0;
                }
                if (numResults == -1) {
                    numResults = results.size();
                }
                int endIndex = Math.min(startIndex + numResults, results.size() - 1);
                results = results.subList(startIndex, endIndex);
            }
        }
    } catch (Exception e) {
        Log.error(e.getMessage(), e);
    } finally {
        try {
            if (ctx != null) {
                ctx.setRequestControls(null);
                ctx.close();
            }
            if (ctx2 != null) {
                ctx2.setRequestControls(null);
                ctx2.close();
            }
        } catch (Exception ignored) {
        // Ignore.
        }
    }
    return results;
}
Also used : PagedResultsResponseControl(javax.naming.ldap.PagedResultsResponseControl) ArrayList(java.util.ArrayList) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) GroupNotFoundException(org.jivesoftware.openfire.group.GroupNotFoundException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) SortControl(javax.naming.ldap.SortControl) Control(javax.naming.ldap.Control) SortControl(javax.naming.ldap.SortControl) PagedResultsControl(javax.naming.ldap.PagedResultsControl) PagedResultsResponseControl(javax.naming.ldap.PagedResultsResponseControl) SearchControls(javax.naming.directory.SearchControls) JiveInitialLdapContext(org.jivesoftware.util.JiveInitialLdapContext) LdapContext(javax.naming.ldap.LdapContext) PagedResultsControl(javax.naming.ldap.PagedResultsControl)

Example 8 with SearchControls

use of javax.naming.directory.SearchControls in project Openfire by igniterealtime.

the class LdapManager method retrieveListCount.

/**
     * Generic routine for retrieving the number of available results from the LDAP server that
     * match the passed search filter.  This routine also accounts for paging settings and
     * alternate DNs.
     *
     * The passed in filter string needs to be pre-prepared!  In other words, nothing will be changed
     * in the string before it is used as a string.
     *
     * @param attribute LDAP attribute to be pulled from each result and used in the query.
     *     Typically pulled from this manager.
     * @param searchFilter Filter to use to perform the search.  Typically pulled from this manager.
     * @return The number of entries that match the filter.
     */
public Integer retrieveListCount(String attribute, String searchFilter) {
    int pageSize = -1;
    String pageSizeStr = properties.get("ldap.pagedResultsSize");
    if (pageSizeStr != null) {
        try {
            pageSize = Integer.parseInt(pageSizeStr);
        /* radix -1 is invalid */
        } catch (NumberFormatException e) {
        // poorly formatted number, ignoring
        }
    }
    LdapContext ctx = null;
    LdapContext ctx2 = null;
    Integer count = 0;
    try {
        ctx = getContext(baseDN);
        // Set up request controls, if appropriate.
        List<Control> baseTmpRequestControls = new ArrayList<>();
        if (pageSize > 0) {
            // Server side paging.
            baseTmpRequestControls.add(new PagedResultsControl(pageSize, Control.NONCRITICAL));
        }
        Control[] baseRequestControls = baseTmpRequestControls.toArray(new Control[baseTmpRequestControls.size()]);
        ctx.setRequestControls(baseRequestControls);
        SearchControls searchControls = new SearchControls();
        // See if recursive searching is enabled. Otherwise, only search one level.
        if (isSubTreeSearch()) {
            searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        } else {
            searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        }
        searchControls.setReturningAttributes(new String[] { attribute });
        byte[] cookie;
        // Run through all pages of results (one page is also possible  ;)  )
        do {
            cookie = null;
            NamingEnumeration<SearchResult> answer = ctx.search("", searchFilter, searchControls);
            // Examine all of the results on this page
            while (answer.hasMoreElements()) {
                answer.next();
                count++;
            }
            // Examine the paged results control response
            Control[] controls = ctx.getResponseControls();
            if (controls != null) {
                for (Control control : controls) {
                    if (control instanceof PagedResultsResponseControl) {
                        PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
                        cookie = prrc.getCookie();
                    }
                }
            }
            // Close the enumeration.
            answer.close();
            // Re-activate paged results; affects nothing if no paging support
            List<Control> tmpRequestControls = new ArrayList<>();
            if (pageSize > 0) {
                // Server side paging.
                tmpRequestControls.add(new PagedResultsControl(pageSize, cookie, Control.CRITICAL));
            }
            Control[] requestControls = tmpRequestControls.toArray(new Control[tmpRequestControls.size()]);
            ctx.setRequestControls(requestControls);
        } while (cookie != null);
        // Add groups found in alternate DN
        if (alternateBaseDN != null) {
            ctx2 = getContext(alternateBaseDN);
            ctx2.setRequestControls(baseRequestControls);
            // Run through all pages of results (one page is also possible  ;)  )
            do {
                cookie = null;
                NamingEnumeration<SearchResult> answer = ctx2.search("", searchFilter, searchControls);
                // Examine all of the results on this page
                while (answer.hasMoreElements()) {
                    answer.next();
                    count++;
                }
                // Examine the paged results control response
                Control[] controls = ctx2.getResponseControls();
                if (controls != null) {
                    for (Control control : controls) {
                        if (control instanceof PagedResultsResponseControl) {
                            PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
                            cookie = prrc.getCookie();
                        }
                    }
                }
                // Close the enumeration.
                answer.close();
                // Re-activate paged results; affects nothing if no paging support
                List<Control> tmpRequestControls = new ArrayList<>();
                if (pageSize > 0) {
                    // Server side paging.
                    tmpRequestControls.add(new PagedResultsControl(pageSize, cookie, Control.CRITICAL));
                }
                Control[] requestControls = tmpRequestControls.toArray(new Control[tmpRequestControls.size()]);
                ctx2.setRequestControls(requestControls);
            } while (cookie != null);
        }
    } catch (Exception e) {
        Log.error(e.getMessage(), e);
    } finally {
        try {
            if (ctx != null) {
                ctx.setRequestControls(null);
                ctx.close();
            }
            if (ctx2 != null) {
                ctx2.setRequestControls(null);
                ctx2.close();
            }
        } catch (Exception ignored) {
        // Ignore.
        }
    }
    return count;
}
Also used : PagedResultsResponseControl(javax.naming.ldap.PagedResultsResponseControl) ArrayList(java.util.ArrayList) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) GroupNotFoundException(org.jivesoftware.openfire.group.GroupNotFoundException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) Control(javax.naming.ldap.Control) SortControl(javax.naming.ldap.SortControl) PagedResultsControl(javax.naming.ldap.PagedResultsControl) PagedResultsResponseControl(javax.naming.ldap.PagedResultsResponseControl) SearchControls(javax.naming.directory.SearchControls) JiveInitialLdapContext(org.jivesoftware.util.JiveInitialLdapContext) LdapContext(javax.naming.ldap.LdapContext) PagedResultsControl(javax.naming.ldap.PagedResultsControl)

Example 9 with SearchControls

use of javax.naming.directory.SearchControls in project presto by prestodb.

the class LdapFilter method checkForGroupMembership.

private void checkForGroupMembership(String user, DirContext context) throws AuthenticationException {
    if (!groupAuthorizationSearchPattern.isPresent()) {
        return;
    }
    String searchFilter = replaceUser(groupAuthorizationSearchPattern.get(), user);
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    boolean authorized;
    NamingEnumeration<SearchResult> search = null;
    try {
        search = context.search(userBaseDistinguishedName.get(), searchFilter, searchControls);
        authorized = search.hasMoreElements();
    } catch (NamingException e) {
        log.debug("Authentication failed", e.getMessage());
        throw new AuthenticationException(INTERNAL_SERVER_ERROR, "Authentication failed", e);
    } finally {
        if (search != null) {
            try {
                search.close();
            } catch (NamingException ignore) {
            }
        }
    }
    if (!authorized) {
        String message = format("Unauthorized user: User %s not a member of the authorized group", user);
        log.debug("Authorization failed for user. " + message);
        throw new AuthenticationException(UNAUTHORIZED, message);
    }
    log.debug("Authorization succeeded for user %s", user);
}
Also used : SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException)

Example 10 with SearchControls

use of javax.naming.directory.SearchControls in project spring-security by spring-projects.

the class ActiveDirectoryLdapAuthenticationProvider method searchForUser.

private DirContextOperations searchForUser(DirContext context, String username) throws NamingException {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String bindPrincipal = createBindPrincipal(username);
    String searchRoot = rootDn != null ? rootDn : searchRootFromPrincipal(bindPrincipal);
    try {
        return SpringSecurityLdapTemplate.searchForSingleEntryInternal(context, searchControls, searchRoot, searchFilter, new Object[] { bindPrincipal });
    } catch (IncorrectResultSizeDataAccessException incorrectResults) {
        // rethrow
        if (incorrectResults.getActualSize() != 0) {
            throw incorrectResults;
        }
        // If we found no results, then the username/password did not match
        UsernameNotFoundException userNameNotFoundException = new UsernameNotFoundException("User " + username + " not found in directory.", incorrectResults);
        throw badCredentials(userNameNotFoundException);
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException) SearchControls(javax.naming.directory.SearchControls)

Aggregations

SearchControls (javax.naming.directory.SearchControls)59 SearchResult (javax.naming.directory.SearchResult)46 NamingException (javax.naming.NamingException)27 ArrayList (java.util.ArrayList)23 Attributes (javax.naming.directory.Attributes)20 NamingEnumeration (javax.naming.NamingEnumeration)16 Attribute (javax.naming.directory.Attribute)15 DirContext (javax.naming.directory.DirContext)13 InitialDirContext (javax.naming.directory.InitialDirContext)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 IOException (java.io.IOException)4 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 PagedResultsControl (javax.naming.ldap.PagedResultsControl)4