Search in sources :

Example 41 with SearchControls

use of javax.naming.directory.SearchControls in project Payara by payara.

the class LDAPRealm method userSearch.

/**
 * Do anonymous search for the user. Should be unique if exists.
 */
private String userSearch(DirContext ctx, String baseDN, String filter) {
    if (_logger.isLoggable(Level.FINEST)) {
        _logger.log(Level.FINE, "search: baseDN: " + baseDN + "  filter: " + filter);
    }
    String foundDN = null;
    NamingEnumeration namingEnum = null;
    SearchControls ctls = new SearchControls();
    ctls.setReturningAttributes(_dnOnly);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setCountLimit(1);
    try {
        namingEnum = ctx.search(baseDN, filter, ctls);
        if (namingEnum.hasMore()) {
            SearchResult res = (SearchResult) namingEnum.next();
            StringBuffer sb = new StringBuffer();
            // for dn name with '/'
            CompositeName compDN = new CompositeName(res.getName());
            String ldapDN = compDN.get(0);
            sb.append(ldapDN);
            if (res.isRelative()) {
                sb.append(",");
                sb.append(baseDN);
            }
            foundDN = sb.toString();
            if (_logger.isLoggable(Level.FINEST)) {
                _logger.log(Level.FINE, "Found user DN: " + foundDN);
            }
        }
    } catch (Exception e) {
        _logger.log(Level.WARNING, "ldaprealm.searcherror", filter);
        _logger.log(Level.WARNING, "security.exception", e);
    } finally {
        if (namingEnum != null) {
            try {
                namingEnum.close();
            } catch (Exception ex) {
            }
        }
    }
    return foundDN;
}
Also used : StringBuffer(java.lang.StringBuffer) CompositeName(javax.naming.CompositeName) NamingEnumeration(javax.naming.NamingEnumeration) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) LoginException(javax.security.auth.login.LoginException) BadRealmException(com.sun.enterprise.security.auth.realm.BadRealmException) NamingException(javax.naming.NamingException) NoSuchRealmException(com.sun.enterprise.security.auth.realm.NoSuchRealmException) InvalidOperationException(com.sun.enterprise.security.auth.realm.InvalidOperationException) IOException(java.io.IOException) NoSuchUserException(com.sun.enterprise.security.auth.realm.NoSuchUserException)

Example 42 with SearchControls

use of javax.naming.directory.SearchControls in project perun by CESNET.

the class ExtSourceEGISSO method getGroupSubjects.

@Override
public List<Map<String, String>> getGroupSubjects(Map<String, String> attributes) throws InternalErrorException {
    List<Map<String, String>> subjects = new ArrayList<>();
    NamingEnumeration<SearchResult> results = null;
    String query = attributes.get(GroupsManager.GROUPMEMBERSQUERY_ATTRNAME);
    String base = "ou=People,dc=egi,dc=eu";
    List<String> ldapGroupSubjects = new ArrayList<>();
    try {
        SearchControls controls = new SearchControls();
        controls.setTimeLimit(5000);
        results = getContext().search(base, query, controls);
        while (results.hasMore()) {
            SearchResult searchResult = results.next();
            subjects.add(processResultToSubject(searchResult));
        }
    } catch (NamingException e) {
        log.error("LDAP exception during query {}.", query);
        throw new InternalErrorException("LDAP exception during running query " + query, e);
    } finally {
        try {
            if (results != null) {
                results.close();
            }
        } catch (Exception e) {
            log.error("LDAP exception during closing result, while running query '{}'", query);
            throw new InternalErrorException(e);
        }
    }
    return subjects;
}
Also used : ArrayList(java.util.ArrayList) SearchResult(javax.naming.directory.SearchResult) SearchControls(javax.naming.directory.SearchControls) NamingException(javax.naming.NamingException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) HashMap(java.util.HashMap) Map(java.util.Map) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) IOException(java.io.IOException) NamingException(javax.naming.NamingException)

Example 43 with SearchControls

use of javax.naming.directory.SearchControls in project tomcat by apache.

the class JNDIRealm method getUserBySearch.

/**
     * Search the directory to return a User object containing
     * information about the user with the specified username, if
     * found in the directory; otherwise return <code>null</code>.
     *
     * @param context The directory context
     * @param username The username
     * @param attrIds String[]containing names of attributes to retrieve.
     * @return the User object
     * @exception NamingException if a directory server error occurs
     */
protected User getUserBySearch(DirContext context, String username, String[] attrIds) throws NamingException {
    if (username == null || userSearchFormat == null)
        return null;
    // Form the search filter
    String filter = userSearchFormat.format(new String[] { username });
    // Set up the search controls
    SearchControls constraints = new SearchControls();
    if (userSubtree) {
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
    } else {
        constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    }
    constraints.setCountLimit(sizeLimit);
    constraints.setTimeLimit(timeLimit);
    // Specify the attributes to be retrieved
    if (attrIds == null)
        attrIds = new String[0];
    constraints.setReturningAttributes(attrIds);
    NamingEnumeration<SearchResult> results = context.search(userBase, filter, constraints);
    try {
        // Fail if no entries found
        try {
            if (results == null || !results.hasMore()) {
                return null;
            }
        } catch (PartialResultException ex) {
            if (!adCompat)
                throw ex;
            else
                return null;
        }
        // Get result for the first entry found
        SearchResult result = results.next();
        // Check no further entries were found
        try {
            if (results.hasMore()) {
                if (containerLog.isInfoEnabled())
                    containerLog.info("username " + username + " has multiple entries");
                return null;
            }
        } catch (PartialResultException ex) {
            if (!adCompat)
                throw ex;
        }
        String dn = getDistinguishedName(context, userBase, result);
        if (containerLog.isTraceEnabled())
            containerLog.trace("  entry found for " + username + " with dn " + dn);
        // Get the entry's attributes
        Attributes attrs = result.getAttributes();
        if (attrs == null)
            return null;
        // Retrieve value of userPassword
        String password = null;
        if (userPassword != null)
            password = getAttributeValue(userPassword, attrs);
        String userRoleAttrValue = null;
        if (userRoleAttribute != null) {
            userRoleAttrValue = getAttributeValue(userRoleAttribute, attrs);
        }
        // Retrieve values of userRoleName attribute
        ArrayList<String> roles = null;
        if (userRoleName != null)
            roles = addAttributeValues(userRoleName, attrs, roles);
        return new User(username, dn, password, roles, userRoleAttrValue);
    } finally {
        if (results != null) {
            results.close();
        }
    }
}
Also used : Attributes(javax.naming.directory.Attributes) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) PartialResultException(javax.naming.PartialResultException)

Example 44 with SearchControls

use of javax.naming.directory.SearchControls in project zeppelin by apache.

the class ActiveDirectoryGroupRealm method getRoleNamesForUser.

private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException {
    Set<String> roleNames = new LinkedHashSet<>();
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String userPrincipalName = username;
    if (this.principalSuffix != null && userPrincipalName.indexOf('@') < 0) {
        userPrincipalName += principalSuffix;
    }
    String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))";
    Object[] searchArguments = new Object[] { userPrincipalName };
    NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls);
    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();
        if (log.isDebugEnabled()) {
            log.debug("Retrieving group names for user [" + sr.getName() + "]");
        }
        Attributes attrs = sr.getAttributes();
        if (attrs != null) {
            NamingEnumeration ae = attrs.getAll();
            while (ae.hasMore()) {
                Attribute attr = (Attribute) ae.next();
                if (attr.getID().equals("memberOf")) {
                    Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr);
                    if (log.isDebugEnabled()) {
                        log.debug("Groups found for user [" + username + "]: " + groupNames);
                    }
                    Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames);
                    roleNames.addAll(rolesForGroups);
                }
            }
        }
    }
    return roleNames;
}
Also used : Attribute(javax.naming.directory.Attribute) Attributes(javax.naming.directory.Attributes) SearchControls(javax.naming.directory.SearchControls) NamingEnumeration(javax.naming.NamingEnumeration) SearchResult(javax.naming.directory.SearchResult)

Example 45 with SearchControls

use of javax.naming.directory.SearchControls in project zeppelin by apache.

the class ActiveDirectoryGroupRealm method searchForUserName.

public List<String> searchForUserName(String containString, LdapContext ldapContext) throws NamingException {
    List<String> userNameList = new ArrayList<>();
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String searchFilter = "(&(objectClass=*)(userPrincipalName=*" + containString + "*))";
    Object[] searchArguments = new Object[] { containString };
    NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls);
    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();
        if (log.isDebugEnabled()) {
            log.debug("Retrieving userprincipalname names for user [" + sr.getName() + "]");
        }
        Attributes attrs = sr.getAttributes();
        if (attrs != null) {
            NamingEnumeration ae = attrs.getAll();
            while (ae.hasMore()) {
                Attribute attr = (Attribute) ae.next();
                if (attr.getID().toLowerCase().equals("cn")) {
                    userNameList.addAll(LdapUtils.getAllAttributeValues(attr));
                }
            }
        }
    }
    return userNameList;
}
Also used : Attribute(javax.naming.directory.Attribute) Attributes(javax.naming.directory.Attributes) SearchControls(javax.naming.directory.SearchControls) NamingEnumeration(javax.naming.NamingEnumeration) SearchResult(javax.naming.directory.SearchResult)

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