Example usage for javax.naming.directory SearchControls SearchControls

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

Introduction

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

Prototype

public SearchControls() 

Source Link

Document

Constructs a search constraints using defaults.

Usage

From source file:org.lsc.jndi.JndiServices.java

/**
 * Search for an entry.//from   w w w  .  j av a2  s  .co m
 *
 * This method is a simple LDAP search operation with SUBTREE search
 * control
 *
 * @param base
 *                the base of the search operation
 * @param filter
 *                the filter of the search operation
 * @return the entry or null if not found
 * @throws NamingException
 *                 thrown if something goes wrong
 */
public SearchResult getEntry(final String base, final String filter) throws NamingException {
    SearchControls sc = new SearchControls();
    return getEntry(base, filter, sc);
}

From source file:org.pentaho.test.platform.plugin.services.security.userrole.ldap.DefaultLdapUserRoleListServiceTests.java

/**
 * Search for all users starting at <code>ou=groups</code>, looking for objects with
 * <code>(&(objectClass=groupOfUniqueNames)(cn={0}))</code>, and extracting the <code>uid</code> token of the
 * <code>uniqueMember</code> attribute. This search implies that the schema is setup such that a user's roles come
 * from that user's DN being present in the <code>uniqueMember</code> attribute of a child object under the
 * <code>ou=groups</code> object.
 *//*from w  w w .ja  va2s  .  c om*/
@Test
public void testGetUsernamesInRole3() {
    SearchControls con1 = new SearchControls();
    con1.setReturningAttributes(new String[] { "uniqueMember" }); //$NON-NLS-1$

    LdapSearchParamsFactory paramFactory = new LdapSearchParamsFactoryImpl("ou=groups", //$NON-NLS-1$
            "(&(objectClass=groupOfUniqueNames)(cn={0}))", con1); //$NON-NLS-1$

    Transformer transformer1 = new SearchResultToAttrValueList("uniqueMember", "uid"); //$NON-NLS-1$ //$NON-NLS-2$

    GrantedAuthorityToString transformer2 = new GrantedAuthorityToString();

    LdapSearch usernamesInRoleSearch = new GenericLdapSearch(getContextSource(), paramFactory, transformer1,
            transformer2);

    DefaultLdapUserRoleListService userRoleListService = new DefaultLdapUserRoleListService();

    userRoleListService.setUsernamesInRoleSearch(usernamesInRoleSearch);

    List<String> res = userRoleListService.getUsersInRole(null, "DEVELOPMENT"); //$NON-NLS-1$

    assertTrue(res.contains("pat")); //$NON-NLS-1$
    assertTrue(res.contains("tiffany")); //$NON-NLS-1$

    if (logger.isDebugEnabled()) {
        logger.debug("results of getUsernamesInRole3(): " + res); //$NON-NLS-1$
    }
}

From source file:org.apache.directory.studio.ldapbrowser.core.jobs.ImportDsmlRunnable.java

/**
 * Returns the {@link SearchControls} object associated with the request.
 *
 * @param request/*from   w w  w  . j  a v a2  s. c  om*/
 *      the search request
 * @return
 *      the associated {@link SearchControls} object
 */
private SearchControls getSearchControls(SearchRequest request) {
    SearchControls controls = new SearchControls();

    // Scope
    switch (request.getScope()) {
    case OBJECT:
        controls.setSearchScope(SearchControls.OBJECT_SCOPE);
        break;
    case ONELEVEL:
        controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        break;
    case SUBTREE:
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        break;
    default:
        controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    }

    // Returning attributes
    List<String> returningAttributes = new ArrayList<String>();
    for (String attribute : request.getAttributes()) {
        returningAttributes.add(attribute);
    }
    // If the returning attributes are empty, we need to return the user attributes
    // [Cf. RFC 2251 - "There are two special values which may be used: an empty 
    //  list with no attributes, and the attribute description string '*'.  Both of 
    //  these signify that all user attributes are to be returned."]
    if (returningAttributes.size() == 0) {
        returningAttributes.add("*"); //$NON-NLS-1$
    }

    controls.setReturningAttributes(returningAttributes.toArray(new String[0]));

    // Size Limit
    controls.setCountLimit(request.getSizeLimit());

    // Time Limit
    controls.setTimeLimit(request.getTimeLimit());

    return controls;
}

From source file:org.pentaho.test.platform.plugin.services.security.userrole.ldap.DefaultLdapUserRoleListServiceTest.java

/**
 * Search for all users starting at <code>ou=groups</code>, looking for objects with
 * <code>(&(objectClass=groupOfUniqueNames)(cn={0}))</code>, and extracting the <code>uid</code> token of the
 * <code>uniqueMember</code> attribute. This search implies that the schema is setup such that a user's roles come
 * from that user's DN being present in the <code>uniqueMember</code> attribute of a child object under the
 * <code>ou=groups</code> object.
 *//*from   ww w.j a va  2s  .  c  o m*/
@Test
public void testGetUsernamesInRole3() {
    SearchControls con1 = new SearchControls();
    con1.setReturningAttributes(new String[] { "uniqueMember" }); //$NON-NLS-1$

    LdapSearchParamsFactory paramFactory = new LdapSearchParamsFactoryImpl("ou=groups", //$NON-NLS-1$
            "(&(objectClass=groupOfUniqueNames)(cn={0}))", con1); //$NON-NLS-1$

    Transformer transformer1 = new SearchResultToAttrValueList("uniqueMember", "uid"); //$NON-NLS-1$ //$NON-NLS-2$

    GrantedAuthorityToString transformer2 = new GrantedAuthorityToString();

    LdapSearch usernamesInRoleSearch = new GenericLdapSearch(getContextSource(), paramFactory, transformer1,
            transformer2);

    DefaultLdapUserRoleListService userRoleListService = getDefaultLdapUserRoleListService();

    userRoleListService.setUsernamesInRoleSearch(usernamesInRoleSearch);

    List<String> res = userRoleListService.getUsersInRole(null, "DEVELOPMENT"); //$NON-NLS-1$

    assertTrue(res.contains("pat")); //$NON-NLS-1$
    assertTrue(res.contains("tiffany")); //$NON-NLS-1$

    if (logger.isDebugEnabled()) {
        logger.debug("results of getUsernamesInRole3(): " + res); //$NON-NLS-1$
    }
}

From source file:org.apache.nifi.ldap.tenants.LdapUserGroupProvider.java

/**
 * Reloads the tenants.//from   ww w  .  j av  a2s. c  o m
 */
private void load(final ContextSource contextSource) {
    // create the ldapTemplate based on the context source. use a single source context to use the same connection
    // to support paging when configured
    final SingleContextSource singleContextSource = new SingleContextSource(contextSource.getReadOnlyContext());
    final LdapTemplate ldapTemplate = new LdapTemplate(singleContextSource);

    try {
        final List<User> userList = new ArrayList<>();
        final List<Group> groupList = new ArrayList<>();

        // group dn -> user identifiers lookup
        final Map<String, Set<String>> groupToUserIdentifierMappings = new HashMap<>();

        // user dn -> user lookup
        final Map<String, User> userLookup = new HashMap<>();

        if (performUserSearch) {
            // search controls
            final SearchControls userControls = new SearchControls();
            userControls.setSearchScope(userSearchScope.ordinal());

            // consider paging support for users
            final DirContextProcessor userProcessor;
            if (pageSize == null) {
                userProcessor = new NullDirContextProcessor();
            } else {
                userProcessor = new PagedResultsDirContextProcessor(pageSize);
            }

            // looking for objects matching the user object class
            final AndFilter userFilter = new AndFilter();
            userFilter.and(new EqualsFilter("objectClass", userObjectClass));

            // if a filter has been provided by the user, we add it to the filter
            if (StringUtils.isNotBlank(userSearchFilter)) {
                userFilter.and(new HardcodedFilter(userSearchFilter));
            }

            do {
                userList.addAll(ldapTemplate.search(userSearchBase, userFilter.encode(), userControls,
                        new AbstractContextMapper<User>() {
                            @Override
                            protected User doMapFromContext(DirContextOperations ctx) {
                                // get the user identity
                                final String identity = getUserIdentity(ctx);

                                // build the user
                                final User user = new User.Builder().identifierGenerateFromSeed(identity)
                                        .identity(identity).build();

                                // store the user for group member later
                                userLookup.put(getReferencedUserValue(ctx), user);

                                if (StringUtils.isNotBlank(userGroupNameAttribute)) {
                                    final Attribute attributeGroups = ctx.getAttributes()
                                            .get(userGroupNameAttribute);

                                    if (attributeGroups == null) {
                                        logger.warn("User group name attribute [" + userGroupNameAttribute
                                                + "] does not exist. Ignoring group membership.");
                                    } else {
                                        try {
                                            final NamingEnumeration<String> groupValues = (NamingEnumeration<String>) attributeGroups
                                                    .getAll();
                                            while (groupValues.hasMoreElements()) {
                                                // store the group -> user identifier mapping
                                                groupToUserIdentifierMappings
                                                        .computeIfAbsent(groupValues.next(),
                                                                g -> new HashSet<>())
                                                        .add(user.getIdentifier());
                                            }
                                        } catch (NamingException e) {
                                            throw new AuthorizationAccessException(
                                                    "Error while retrieving user group name attribute ["
                                                            + userIdentityAttribute + "].");
                                        }
                                    }
                                }

                                return user;
                            }
                        }, userProcessor));
            } while (hasMorePages(userProcessor));
        }

        if (performGroupSearch) {
            final SearchControls groupControls = new SearchControls();
            groupControls.setSearchScope(groupSearchScope.ordinal());

            // consider paging support for groups
            final DirContextProcessor groupProcessor;
            if (pageSize == null) {
                groupProcessor = new NullDirContextProcessor();
            } else {
                groupProcessor = new PagedResultsDirContextProcessor(pageSize);
            }

            // looking for objects matching the group object class
            AndFilter groupFilter = new AndFilter();
            groupFilter.and(new EqualsFilter("objectClass", groupObjectClass));

            // if a filter has been provided by the user, we add it to the filter
            if (StringUtils.isNotBlank(groupSearchFilter)) {
                groupFilter.and(new HardcodedFilter(groupSearchFilter));
            }

            do {
                groupList.addAll(ldapTemplate.search(groupSearchBase, groupFilter.encode(), groupControls,
                        new AbstractContextMapper<Group>() {
                            @Override
                            protected Group doMapFromContext(DirContextOperations ctx) {
                                final String dn = ctx.getDn().toString();

                                // get the group identity
                                final String name = getGroupName(ctx);

                                // get the value of this group that may associate it to users
                                final String referencedGroupValue = getReferencedGroupValue(ctx);

                                if (!StringUtils.isBlank(groupMemberAttribute)) {
                                    Attribute attributeUsers = ctx.getAttributes().get(groupMemberAttribute);
                                    if (attributeUsers == null) {
                                        logger.warn("Group member attribute [" + groupMemberAttribute
                                                + "] does not exist. Ignoring group membership.");
                                    } else {
                                        try {
                                            final NamingEnumeration<String> userValues = (NamingEnumeration<String>) attributeUsers
                                                    .getAll();
                                            while (userValues.hasMoreElements()) {
                                                final String userValue = userValues.next();

                                                if (performUserSearch) {
                                                    // find the user by it's referenced attribute and add the identifier to this group
                                                    final User user = userLookup.get(userValue);

                                                    // ensure the user is known
                                                    if (user != null) {
                                                        groupToUserIdentifierMappings
                                                                .computeIfAbsent(referencedGroupValue,
                                                                        g -> new HashSet<>())
                                                                .add(user.getIdentifier());
                                                    } else {
                                                        logger.warn(String.format(
                                                                "%s contains member %s but that user was not found while searching users. Ignoring group membership.",
                                                                name, userValue));
                                                    }
                                                } else {
                                                    // since performUserSearch is false, then the referenced group attribute must be blank... the user value must be the dn
                                                    final String userDn = userValue;

                                                    final String userIdentity;
                                                    if (useDnForUserIdentity) {
                                                        // use the user value to avoid the unnecessary look up
                                                        userIdentity = userDn;
                                                    } else {
                                                        // lookup the user to extract the user identity
                                                        userIdentity = getUserIdentity(
                                                                (DirContextAdapter) ldapTemplate
                                                                        .lookup(userDn));
                                                    }

                                                    // build the user
                                                    final User user = new User.Builder()
                                                            .identifierGenerateFromSeed(userIdentity)
                                                            .identity(userIdentity).build();

                                                    // add this user
                                                    userList.add(user);
                                                    groupToUserIdentifierMappings
                                                            .computeIfAbsent(referencedGroupValue,
                                                                    g -> new HashSet<>())
                                                            .add(user.getIdentifier());
                                                }
                                            }
                                        } catch (NamingException e) {
                                            throw new AuthorizationAccessException(
                                                    "Error while retrieving group name attribute ["
                                                            + groupNameAttribute + "].");
                                        }
                                    }
                                }

                                // build this group
                                final Group.Builder groupBuilder = new Group.Builder()
                                        .identifierGenerateFromSeed(name).name(name);

                                // add all users that were associated with this referenced group attribute
                                if (groupToUserIdentifierMappings.containsKey(referencedGroupValue)) {
                                    groupToUserIdentifierMappings.remove(referencedGroupValue)
                                            .forEach(userIdentifier -> groupBuilder.addUser(userIdentifier));
                                }

                                return groupBuilder.build();
                            }
                        }, groupProcessor));
            } while (hasMorePages(groupProcessor));

            // any remaining groupDn's were referenced by a user but not found while searching groups
            groupToUserIdentifierMappings.forEach((referencedGroupValue, userIdentifiers) -> {
                logger.warn(String.format(
                        "[%s] are members of %s but that group was not found while searching users. Ignoring group membership.",
                        StringUtils.join(userIdentifiers, ", "), referencedGroupValue));
            });
        } else {
            // since performGroupSearch is false, then the referenced user attribute must be blank... the group value must be the dn

            // groups are not being searched so lookup any groups identified while searching users
            groupToUserIdentifierMappings.forEach((groupDn, userIdentifiers) -> {
                final String groupName;
                if (useDnForGroupName) {
                    // use the dn to avoid the unnecessary look up
                    groupName = groupDn;
                } else {
                    groupName = getGroupName((DirContextAdapter) ldapTemplate.lookup(groupDn));
                }

                // define the group
                final Group.Builder groupBuilder = new Group.Builder().identifierGenerateFromSeed(groupName)
                        .name(groupName);

                // add each user
                userIdentifiers.forEach(userIdentifier -> groupBuilder.addUser(userIdentifier));

                // build the group
                groupList.add(groupBuilder.build());
            });
        }

        // record the updated tenants
        tenants.set(new TenantHolder(new HashSet<>(userList), new HashSet<>(groupList)));
    } finally {
        singleContextSource.destroy();
    }
}

From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java

public boolean isValidPassword(String serverName, Object existingCredentials)
        throws DirectoryServerManagerException {

    DirContext dirContext;//from  ww w  . j a va 2s  .  co m
    try {
        dirContext = this.connectionSource.getContext();
    } catch (UserStoreException e) {
        throw new DirectoryServerManagerException("Unable to retrieve directory connection.", e);
    }

    //first search the existing user entry.
    String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String searchFilter = getServicePrincipleFilter(serverName);

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(new String[] { LDAPServerManagerConstants.LDAP_PASSWORD });

    try {
        NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, searchFilter,
                searchControls);
        // here we assume only one user
        while (namingEnumeration.hasMore()) {

            SearchResult searchResult = namingEnumeration.next();
            Attributes attributes = searchResult.getAttributes();

            Attribute userPassword = attributes.get(LDAPServerManagerConstants.LDAP_PASSWORD);

            NamingEnumeration passwords = userPassword.getAll();

            String passwordHashMethod = null;
            if (passwords.hasMore()) {
                byte[] byteArray = (byte[]) passwords.next();
                String password = new String(byteArray, StandardCharsets.UTF_8);

                if (password.startsWith("{")) {
                    passwordHashMethod = password.substring(password.indexOf("{") + 1, password.indexOf("}"));
                }

                return password.equals(getPasswordToStore((String) existingCredentials, passwordHashMethod));
            }
        }

    } catch (NamingException e) {
        log.error("Failed, validating password. Can not access the directory service", e);
        throw new DirectoryServerManagerException(
                "Failed, validating password. " + "Can not access the directory service", e);
    } finally {
        try {
            JNDIUtil.closeContext(dirContext);
        } catch (UserStoreException e) {
            log.error("Unable to close directory context.", e);
        }
    }

    return false;
}

From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java

@SuppressWarnings("rawtypes")
@Override/*  w  ww  .java 2 s.  com*/
public void doUpdateCredential(String userName, Object newCredential, Object oldCredential)
        throws UserStoreException {

    DirContext dirContext = this.connectionSource.getContext();
    DirContext subDirContext = null;
    // first search the existing user entry.
    String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String searchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(new String[] { "userPassword" });

    NamingEnumeration<SearchResult> namingEnumeration = null;
    NamingEnumeration passwords = null;

    try {
        namingEnumeration = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControls);
        // here we assume only one user
        // TODO: what to do if there are more than one user
        SearchResult searchResult = null;
        String passwordHashMethod = realmConfig.getUserStoreProperty(PASSWORD_HASH_METHOD);
        while (namingEnumeration.hasMore()) {
            searchResult = namingEnumeration.next();

            String dnName = searchResult.getName();
            subDirContext = (DirContext) dirContext.lookup(searchBase);

            Attribute passwordAttribute = new BasicAttribute("userPassword");
            passwordAttribute.add(
                    UserCoreUtil.getPasswordToStore((String) newCredential, passwordHashMethod, kdcEnabled));
            BasicAttributes basicAttributes = new BasicAttributes(true);
            basicAttributes.put(passwordAttribute);
            subDirContext.modifyAttributes(dnName, DirContext.REPLACE_ATTRIBUTE, basicAttributes);
        }
        // we check whether both carbon admin entry and ldap connection
        // entry are the same
        if (searchResult.getNameInNamespace()
                .equals(realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_NAME))) {
            this.connectionSource.updateCredential((String) newCredential);
        }

    } catch (NamingException e) {
        String errorMessage = "Can not access the directory service for user : " + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(passwords);
        JNDIUtil.closeNamingEnumeration(namingEnumeration);

        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }
}

From source file:org.openiam.spml2.spi.example.ShellConnectorImpl.java

private NamingEnumeration search(ManagedSystemObjectMatch matchObj, LdapContext ctx, String searchValue,
        String[] attrAry) throws NamingException {
    SearchControls searchCtls = new SearchControls();

    searchCtls.setReturningAttributes(attrAry);

    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String searchFilter = matchObj.getSearchFilter();
    // replace the place holder in the search filter
    searchFilter = searchFilter.replace("?", searchValue);

    System.out.println("Search Filter=" + searchFilter);
    System.out.println("BaseDN=" + matchObj.getBaseDn());

    return ctx.search(matchObj.getSearchBaseDn(), searchFilter, searchCtls);

}

From source file:org.pentaho.test.platform.plugin.services.security.userrole.ldap.DefaultLdapUserRoleListServiceTests.java

/**
 * Search for all users starting at <code>ou=groups</code>, looking for objects with
 * <code>(&(objectClass=groupOfUniqueNames)(cn={0}))</code>, and extracting the <code>uid</code> token of the
 * <code>uniqueMember</code> attribute. This search implies that the schema is setup such that a user's roles come
 * from that user's DN being present in the <code>uniqueMember</code> attribute of a child object under the
 * <code>ou=groups</code> object.
 * /*  w  w  w.ja  v a 2  s .com*/
 * @throws Exception
 */
@Test
public void testGetUsernamesInRole4() throws Exception {
    SearchControls con1 = new SearchControls();
    con1.setReturningAttributes(new String[] { "uniqueMember" }); //$NON-NLS-1$

    LdapSearchParamsFactory paramFactory = new LdapSearchParamsFactoryImpl("ou=groups", //$NON-NLS-1$
            "(&(objectClass=groupOfUniqueNames)(cn={0}))", con1); //$NON-NLS-1$

    Transformer transformer1 = new SearchResultToAttrValueList("uniqueMember", "uid"); //$NON-NLS-1$ //$NON-NLS-2$

    GrantedAuthorityToString transformer2 = new GrantedAuthorityToString();

    LdapSearch usernamesInRoleSearch = new GenericLdapSearch(getContextSource(), paramFactory, transformer1,
            transformer2);

    SearchControls con2 = new SearchControls();
    con2.setReturningAttributes(new String[] { "uid" }); //$NON-NLS-1$

    LdapSearchParamsFactory paramFactory2 = new LdapSearchParamsFactoryImpl("ou=users", //$NON-NLS-1$
            "(businessCategory=cn={0}*)", con2); //$NON-NLS-1$

    Transformer transformer3 = new SearchResultToAttrValueList("uid"); //$NON-NLS-1$

    GrantedAuthorityToString transformer4 = new GrantedAuthorityToString();

    LdapSearch usernamesInRoleSearch2 = new GenericLdapSearch(getContextSource(), paramFactory2, transformer3,
            transformer4);

    Set searches = new HashSet();
    searches.add(usernamesInRoleSearch);
    searches.add(usernamesInRoleSearch2);
    UnionizingLdapSearch unionSearch = new UnionizingLdapSearch(searches);
    unionSearch.afterPropertiesSet();

    DefaultLdapUserRoleListService userRoleListService = new DefaultLdapUserRoleListService();

    userRoleListService.setUsernamesInRoleSearch(unionSearch);

    List<String> res = userRoleListService.getUsersInRole(null, "DEV"); //$NON-NLS-1$

    assertTrue(res.contains("pat")); //$NON-NLS-1$
    assertTrue(res.contains("tiffany")); //$NON-NLS-1$

    if (logger.isDebugEnabled()) {
        logger.debug("results of getUsernamesInRole4() with role=ROLE_DEV: " + res); //$NON-NLS-1$
    }

    res = userRoleListService.getUsersInRole(null, "DEVELOPMENT"); //$NON-NLS-1$

    assertTrue(res.contains("pat")); //$NON-NLS-1$
    assertTrue(res.contains("tiffany")); //$NON-NLS-1$

    if (logger.isDebugEnabled()) {
        logger.debug("results of getUsernamesInRole4() with role=DEVELOPMENT: " + res); //$NON-NLS-1$
    }

}

From source file:com.funambol.LDAP.security.LDAPUserProvisioningOfficer.java

/**
 * return the user dn of an ldap entry/*from  w w w .j  a va2s .  co m*/
 * 
 * search: base, filter, attrs, user, pass
 * @return
 */
protected SearchResult ldapSearch(String bindUser, String bindPass, String base, String filter,
        String[] attributes) {
    SearchResult ret = null;
    Hashtable<String, Object> bindEnv = new Hashtable<String, Object>(11);
    bindEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    bindEnv.put(Context.PROVIDER_URL, getLdapUrl());

    // remove null attributes
    List<String> goodAttributes = new ArrayList<String>();
    for (String s : attributes) {
        if (s != null) {
            goodAttributes.add(s);
        }
    }

    // get the DN 
    DirContext authenticationContext;
    try {
        SearchControls ctls = new SearchControls();
        ctls.setCountLimit(1);
        ctls.setReturningObjFlag(true);
        ctls.setReturningAttributes(goodAttributes.toArray(new String[0]));
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // Authenticate as  User and password  
        if (bindUser != null && bindPass != null) {
            log.debug("NBinding with credential as user: " + bindUser);
            bindEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
            bindEnv.put(Context.SECURITY_PRINCIPAL, bindUser);
            bindEnv.put(Context.SECURITY_CREDENTIALS, bindPass);
        }
        authenticationContext = new InitialDirContext(bindEnv);
        // %u, %d in baseDN are still expanded 
        NamingEnumeration<SearchResult> answer;
        try {
            answer = authenticationContext.search(base, filter, ctls);

            if (answer.hasMore()) {
                ret = (SearchResult) answer.next();
            }
        } catch (NamingException e) {
            log.warn("Error while searching user with filter [" + filter + "]: " + e.getMessage());
        }
        authenticationContext.close();
        return ret;

    } catch (NamingException e) {
        log.error("Error while creating context: " + e.getMessage());
        if (e.getCause() != null) {
            log.error("Error is: " + e.getCause().getMessage());
        }
        return null;
    }
}