Search in sources :

Example 56 with SearchResult

use of javax.naming.directory.SearchResult 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 57 with SearchResult

use of javax.naming.directory.SearchResult 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 58 with SearchResult

use of javax.naming.directory.SearchResult in project simba-os by cegeka.

the class ActiveDirectoryLoginModuleTest method injection.

@Test
@SuppressWarnings("unchecked")
public void injection() throws Exception {
    when(configurationService.getValue(SimbaConfigurationParameter.ENABLE_AD_GROUPS)).thenReturn(Boolean.FALSE);
    Map<String, String> options = new HashMap<>();
    options.put("primaryServer", "localhost:389");
    options.put("baseDN", "'dc=rsvzinasti,dc=be'");
    options.put("filter", "(&amp;(objectClass=person)(sAMAccountName=%USERNAME%))");
    options.put("searchScope", "subtree");
    options.put("authDomain", "rsvzinasti.be");
    options.put("authAttr", "sAMAccountName");
    options.put("securityLevel", "simple");
    NamingEnumeration attrsNamingEnumeration = mock(NamingEnumeration.class);
    when(attrsNamingEnumeration.hasMore()).thenReturn(true);
    Attributes attrs = mock(Attributes.class);
    when(attrs.getAll()).thenReturn(attrsNamingEnumeration);
    SearchResult searchResult = mock(SearchResult.class);
    when(searchResult.getName()).thenReturn(null);
    when(searchResult.getAttributes()).thenReturn(attrs);
    NamingEnumeration<SearchResult> searchResultNamingEnumeration = mock(NamingEnumeration.class);
    when(searchResultNamingEnumeration.hasMoreElements()).thenReturn(true).thenReturn(false);
    when(searchResultNamingEnumeration.next()).thenReturn(searchResult);
    ArgumentCaptor<String> searchFilter = ArgumentCaptor.forClass(String.class);
    final LdapContext ldapContext = mock(LdapContext.class);
    when(ldapContext.search(eq("'dc=rsvzinasti,dc=be'"), searchFilter.capture(), any(SearchControls.class))).thenReturn(searchResultNamingEnumeration);
    ActiveDirectoryLoginModule loginModule = new ActiveDirectoryLoginModule() {

        @Override
        protected LdapContext tryPrimaryContext(Hashtable<String, String> env) {
            return ldapContext;
        }
    };
    loginModule.setUsername(" u\\*() ");
    loginModule.setPassword(" p\\*() ");
    loginModule.initialize(new Subject(), mock(CallbackHandler.class), Collections.emptyMap(), options);
    boolean result = loginModule.verifyLoginData();
    assertThat(result).isTrue();
    assertThat(searchFilter.getValue()).isEqualTo("(&amp;(objectClass=person)(sAMAccountName= u5c2a282900 ))");
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) HashMap(java.util.HashMap) Hashtable(java.util.Hashtable) Attributes(javax.naming.directory.Attributes) NamingEnumeration(javax.naming.NamingEnumeration) SearchResult(javax.naming.directory.SearchResult) Subject(javax.security.auth.Subject) SearchControls(javax.naming.directory.SearchControls) LdapContext(javax.naming.ldap.LdapContext) Test(org.junit.Test)

Example 59 with SearchResult

use of javax.naming.directory.SearchResult 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 60 with SearchResult

use of javax.naming.directory.SearchResult 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)

Aggregations

SearchResult (javax.naming.directory.SearchResult)95 SearchControls (javax.naming.directory.SearchControls)63 NamingException (javax.naming.NamingException)43 Attributes (javax.naming.directory.Attributes)35 Attribute (javax.naming.directory.Attribute)32 ArrayList (java.util.ArrayList)29 DirContext (javax.naming.directory.DirContext)27 NamingEnumeration (javax.naming.NamingEnumeration)24 InitialDirContext (javax.naming.directory.InitialDirContext)16 Test (org.junit.Test)15 LdapContext (javax.naming.ldap.LdapContext)13 IOException (java.io.IOException)9 BasicAttributes (javax.naming.directory.BasicAttributes)9 DistinguishedName (org.springframework.ldap.core.DistinguishedName)9 DirContextAdapter (org.springframework.ldap.core.DirContextAdapter)7 HashMap (java.util.HashMap)6 HashSet (java.util.HashSet)6 Name (javax.naming.Name)6 BasicAttribute (javax.naming.directory.BasicAttribute)6 PartialResultException (javax.naming.PartialResultException)5