Example usage for javax.naming.directory SearchControls SUBTREE_SCOPE

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

Introduction

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

Prototype

int SUBTREE_SCOPE

To view the source code for javax.naming.directory SearchControls SUBTREE_SCOPE.

Click Source Link

Document

Search the entire subtree rooted at the named object.

Usage

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 w w .j a v  a 2 s . c  om
    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:org.jasig.schedassist.impl.ldap.LDAPDelegateCalendarAccountDaoImpl.java

/**
 * /*  w  w w  .  j a v a  2s  . co  m*/
 * @param searchFilter
 * @param owner
 * @return
 */
@SuppressWarnings("unchecked")
protected List<IDelegateCalendarAccount> executeSearchReturnList(final Filter searchFilter,
        final ICalendarAccount owner) {
    SearchControls searchControls = new SearchControls();
    searchControls.setCountLimit(searchResultsLimit);
    searchControls.setTimeLimit(searchTimeLimit);
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    List<IDelegateCalendarAccount> results = Collections.emptyList();
    try {
        results = ldapTemplate.search(baseDn, searchFilter.toString(), searchControls,
                new DefaultDelegateAccountAttributesMapperImpl(ldapAttributesKey, owner));
        if (log.isDebugEnabled()) {
            log.debug("search " + searchFilter + " returned " + results.size() + " results");
        }

        if (isTreatOwnerAttributeAsDistinguishedName() && owner != null
                && owner instanceof HasDistinguishedName) {
            HasDistinguishedName ldapOwnerAccount = (HasDistinguishedName) owner;
            enforceDistinguishedNameMatch(results, ldapOwnerAccount);
        }
        Collections.sort(results, new DelegateDisplayNameComparator());
    } catch (SizeLimitExceededException e) {
        log.debug("search filter exceeded size limit (" + searchResultsLimit + "): " + searchFilter);
    } catch (TimeLimitExceededException e) {
        log.debug("search filter exceeded time limit(" + searchTimeLimit + " milliseconds): " + searchFilter);
    }
    return results;
}

From source file:org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator.java

/**
 * If set to true, a subtree scope search will be performed. If false a single-level
 * search is used.//from w  ww  .  ja  v a 2 s .  c  o m
 *
 * @param searchSubtree set to true to enable searching of the entire tree below the
 * <tt>groupSearchBase</tt>.
 */
public void setSearchSubtree(boolean searchSubtree) {
    int searchScope = searchSubtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE;
    this.searchControls.setSearchScope(searchScope);
}

From source file:org.ligoj.app.plugin.id.ldap.dao.UserLdapRepository.java

/**
 * Return all user entries./*from  www.ja  va  2  s .c om*/
 *
 * @param groups
 *            The existing groups. They will be be used to complete the membership of each returned user.
 * @return all user entries. Key is the user login.
 */
@Override
public Map<String, UserOrg> findAllNoCache(final Map<String, GroupOrg> groups) {

    // List of attributes to retrieve from LDAP.
    final String[] returnAttrs = new String[] { SN_ATTRIBUTE, GIVEN_NAME_ATTRIBUTE, PASSWORD_ATTRIBUTE,
            MAIL_ATTRIBUTE, uidAttribute, departmentAttribute, localIdAttribute, lockedAttribute,
            PWD_ACCOUNT_LOCKED_ATTRIBUTE };

    // Fetch users and their direct attributes
    final List<UserOrg> users = template.search(peopleBaseDn,
            new EqualsFilter(OBJECT_CLASS, peopleClass).encode(), SearchControls.SUBTREE_SCOPE, returnAttrs,
            mapper);

    // INdex the users by the identifier
    final Map<String, UserOrg> result = new HashMap<>();
    for (final UserOrg user : users) {
        user.setGroups(new ArrayList<>());
        result.put(user.getId(), user);
    }

    // Update the memberships of this user
    for (final Entry<String, GroupOrg> groupEntry : groups.entrySet()) {
        updateMembership(result, groupEntry);
    }
    return result;
}

From source file:org.infoscoop.account.ldap.LDAPAccountManager.java

private void setGroup(DirContext context, LDAPAccount user) throws NamingException {

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    //create the filter of group
    Map filters = new HashMap();
    String uniqueMemberAttrName = "uniquemember";
    if (this.propAttrMap.containsKey("org_member"))
        uniqueMemberAttrName = (String) this.propAttrMap.get("org_member");

    filters.put(uniqueMemberAttrName, user.getDn());
    String grpFilter = buildGroupFilterByDN(filters);

    NamingEnumeration grpRes = context.search(groupBase, grpFilter, searchControls);

    List grpList = new ArrayList();

    while (grpRes.hasMoreElements()) {
        SearchResult findGrpEntry = (SearchResult) grpRes.next();
        if (log.isDebugEnabled())
            log.debug("Found Groups: " + findGrpEntry.getAttributes().toString());
        String grpdn = findGrpEntry.getName() + "," + groupBase;

        grpList.add(createLDAPGroup(grpdn, findGrpEntry.getAttributes()));
    }//w w  w.j  av a  2  s  .c  om

    IGroup[] igroup = new IGroup[grpList.size()];

    for (int i = 0; i < igroup.length; i++) {
        igroup[i] = (IGroup) grpList.get(i);
    }
    user.setGroups(igroup);

}

From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java

/**
 * Returns the values of the specified fields for the supplied id. 
 * @see IExternalStorage#getFields(java.lang.String, java.util.List)
 *//*from w ww .java2  s  .  c  o m*/
public Hashtable<String, Object> getFields(String id, List<String> fields) throws UserException {
    Hashtable<String, Object> htReturn = new Hashtable<String, Object>();
    DirContext oDirContext = null;
    NamingEnumeration oNamingEnumeration = null;
    try {
        try {
            oDirContext = new InitialDirContext(_htJNDIEnvironment);
        } catch (NamingException e) {
            _logger.error("Could not create the connection: " + _htJNDIEnvironment);
            throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e);
        }

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] saFields = fields.toArray(new String[0]);
        oScope.setReturningAttributes(saFields);

        String searchFilter = resolveSearchQuery(id);
        try {
            oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope);
        } catch (InvalidSearchFilterException e) {
            StringBuffer sbFailed = new StringBuffer("Wrong filter: ");
            sbFailed.append(searchFilter);
            sbFailed.append(" while searching for attributes '");
            sbFailed.append(fields);
            sbFailed.append("' for id: ");
            sbFailed.append(id);
            _logger.error(sbFailed.toString(), e);
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        } catch (NamingException e) {
            _logger.error("User unknown: " + id);
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        }

        if (!oNamingEnumeration.hasMore()) {
            StringBuffer sbFailed = new StringBuffer("User with id '");
            sbFailed.append(id);
            sbFailed.append("' not found after LDAP search with filter: ");
            sbFailed.append(searchFilter);
            _logger.error(sbFailed.toString());
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next();
        Attributes oAttributes = oSearchResult.getAttributes();
        NamingEnumeration neAttributes = oAttributes.getAll();
        while (neAttributes.hasMore()) {
            Attribute oAttribute = (Attribute) neAttributes.next();
            String sAttributeName = oAttribute.getID();

            if (oAttribute.size() > 1) {
                Vector<Object> vValue = new Vector<Object>();
                NamingEnumeration neAttribute = oAttribute.getAll();
                while (neAttribute.hasMore())
                    vValue.add(neAttribute.next());

                htReturn.put(sAttributeName, vValue);
            } else {
                Object oValue = oAttribute.get();
                if (oValue == null)
                    oValue = "";
                htReturn.put(sAttributeName, oValue);
            }
        }
    } catch (UserException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not retrieve fields: " + fields, e);
        throw new UserException(SystemErrors.ERROR_INTERNAL, e);
    } finally {
        if (oNamingEnumeration != null) {
            try {
                oNamingEnumeration.close();
            } catch (Exception e) {
                _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e);
            }
        }
        if (oDirContext != null) {
            try {
                oDirContext.close();
            } catch (NamingException e) {
                _logger.error("Could not close Dir Context after searching for user with id: " + id, e);
            }
        }
    }
    return htReturn;
}

From source file:com.alfaariss.oa.authentication.password.jndi.JNDIProtocolResource.java

private boolean doBind(String sUserID, String sPassword) throws OAException, UserException {
    StringBuffer sbTemp = null;/*w w w .jav  a  2 s  .co m*/
    DirContext oDirContext = null;
    String sQuery = null;
    String sRelUserDn = null;
    boolean bResult = false;
    NamingEnumeration enumSearchResults = null;

    Hashtable<String, String> htEnvironment = new Hashtable<String, String>();

    htEnvironment.put(Context.PROVIDER_URL, _sJNDIUrl);
    htEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, _sDriver);
    htEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple");

    if (_bSSL) {
        htEnvironment.put(Context.SECURITY_PROTOCOL, "ssl");
    }

    if (_sPrincipalDn.length() <= 0)
    // If no principal dn is known, we do a simple binding
    {
        String sEscUserID = JNDIUtil.escapeDN(sUserID);
        _logger.debug("Escaped user: " + sEscUserID);
        sbTemp = new StringBuffer(_sUserDn);
        sbTemp.append('=');
        sbTemp.append(sEscUserID);
        sbTemp.append(", ");
        sbTemp.append(_sBaseDn);
        htEnvironment.put(Context.SECURITY_PRINCIPAL, sbTemp.toString());

        htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword);

        try {
            oDirContext = new InitialDirContext(htEnvironment);
            bResult = true;
        } catch (AuthenticationException e) {
            // If supplied credentials are invalid or when authentication fails
            // while accessing the directory or naming service.
            _logger.debug("Could not authenticate user (invalid password): " + sUserID, e);
        } catch (CommunicationException eC) {
            // If communication with the directory or naming service fails.
            _logger.warn("A communication error has occured", eC);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } catch (NamingException eN) {
            // The initial dir context could not be created.
            _logger.warn("A naming error has occured", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } finally {

            try {
                if (oDirContext != null) {
                    oDirContext.close();
                }
            } catch (Exception e) {
                _logger.warn("Could not close connection with '" + _sJNDIUrl + '\'', e);
            }
        }
    } else //search through the subtree
    {
        // 1 - Try to bind to LDAP using the security principal's DN and its password
        htEnvironment.put(Context.SECURITY_PRINCIPAL, _sPrincipalDn);
        htEnvironment.put(Context.SECURITY_CREDENTIALS, _sPrincipalPwd);

        try {
            oDirContext = new InitialDirContext(htEnvironment);
        } catch (AuthenticationException eA) {
            _logger.warn("Could not bind to LDAP server", eA);
            throw new OAException(SystemErrors.ERROR_RESOURCE_CONNECT);
        } catch (CommunicationException eC) {
            _logger.warn("A communication error has occured", eC);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } catch (NamingException eN) {
            _logger.warn("A naming error has occured", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        // 2 - Search through the context for user's DN relative to the base DN
        sQuery = resolveSearchQuery(sUserID);

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

        try {
            enumSearchResults = oDirContext.search(_sBaseDn, sQuery, oScope);
        } catch (NamingException eN) {
            _logger.warn("User id not found in password backend for user: " + sUserID, eN);
            throw new UserException(UserEvent.AUTHN_METHOD_NOT_SUPPORTED);
        } finally {
            try {

                oDirContext.close();
                oDirContext = null;

            } catch (Exception e) {
                _logger.warn("Could not close connection with '" + _sJNDIUrl + "'", e);
            }
        }

        try {
            if (!enumSearchResults.hasMoreElements()) {
                StringBuffer sb = new StringBuffer("User '");
                sb.append(sUserID);
                sb.append("' not found during LDAP search. The filter was: '");
                sb.append(sQuery);
                sb.append("'");
                _logger.warn(sb.toString());
                throw new UserException(UserEvent.AUTHN_METHOD_NOT_SUPPORTED);
            }

            SearchResult searchResult = (SearchResult) enumSearchResults.next();
            sRelUserDn = searchResult.getName();
            if (sRelUserDn == null) {
                _logger.warn("no user dn was returned for '" + sUserID + "'.");
                throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
            }
        } catch (NamingException eN) {

            _logger.warn("failed to fetch profile of user '" + sUserID + "'.", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        // 3 - Bind user using supplied credentials
        sbTemp = new StringBuffer(sRelUserDn);
        sbTemp.append(",");
        sbTemp.append(_sBaseDn);

        htEnvironment.put(Context.SECURITY_PRINCIPAL, sbTemp.toString());
        htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword);

        try {
            oDirContext = new InitialDirContext(htEnvironment);
            bResult = true;
        } catch (AuthenticationException e) {
            _logger.debug("Could not authenticate user (invalid password): " + sUserID, e);
        } catch (CommunicationException eC) {
            _logger.warn("A communication error has occured", eC);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } catch (NamingException eN) {
            _logger.warn("A naming error has occured", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } finally {
            try {
                if (oDirContext != null) {
                    oDirContext.close();
                }
            } catch (Exception e) {
                _logger.warn("Could not close connection with '" + _sJNDIUrl + "'.", e);
            }
        }
    }
    return bResult;
}

From source file:iplatform.admin.ui.server.auth.ad.ActiveDirectoryLdapAuthenticationProvider.java

@SuppressWarnings("deprecation")
private DirContextOperations searchForUser(DirContext ctx, String username) throws NamingException {
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String searchFilter = "(&(objectClass=user)(userPrincipalName={0}))";

    final String bindPrincipal = createBindPrincipal(username);

    String searchRoot = rootDn != null ? rootDn : searchRootFromPrincipal(bindPrincipal);

    try {/*from   ww w  .java 2  s.c om*/
        return SpringSecurityLdapTemplate.searchForSingleEntryInternal(ctx, searchCtls, searchRoot,
                searchFilter, new Object[] { bindPrincipal });
    } catch (IncorrectResultSizeDataAccessException incorrectResults) {
        if (incorrectResults.getActualSize() == 0) {
            UsernameNotFoundException userNameNotFoundException = new UsernameNotFoundException(
                    "User " + username + " not found in directory.", username);
            userNameNotFoundException.initCause(incorrectResults);
            throw badCredentials(userNameNotFoundException);
        }
        // Search should never return multiple results if properly configured, so just rethrow
        throw incorrectResults;
    }
}

From source file:org.apache.zeppelin.service.ShiroAuthenticationService.java

/** Function to extract users from LDAP. */
private List<String> getUserList(JndiLdapRealm r, String searchText, int numUsersToFetch) {
    List<String> userList = new ArrayList<>();
    String userDnTemplate = r.getUserDnTemplate();
    String userDn[] = userDnTemplate.split(",", 2);
    String userDnPrefix = userDn[0].split("=")[0];
    String userDnSuffix = userDn[1];
    JndiLdapContextFactory cf = (JndiLdapContextFactory) r.getContextFactory();
    try {//from   w w w .j  a  va  2s.  c om
        LdapContext ctx = cf.getSystemLdapContext();
        SearchControls constraints = new SearchControls();
        constraints.setCountLimit(numUsersToFetch);
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attrIDs = { userDnPrefix };
        constraints.setReturningAttributes(attrIDs);
        NamingEnumeration result = ctx.search(userDnSuffix, "(" + userDnPrefix + "=*" + searchText + "*)",
                constraints);
        while (result.hasMore()) {
            Attributes attrs = ((SearchResult) result.next()).getAttributes();
            if (attrs.get(userDnPrefix) != null) {
                String currentUser = attrs.get(userDnPrefix).toString();
                userList.add(currentUser.split(":")[1].trim());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error retrieving User list from Ldap Realm", e);
    }
    LOGGER.info("UserList: " + userList);
    return userList;
}

From source file:org.apache.archiva.redback.users.ldap.ctl.DefaultLdapController.java

public Map<String, Collection<String>> findUsersWithRoles(DirContext dirContext)
        throws LdapControllerException {
    Map<String, Collection<String>> usersWithRoles = new HashMap<String, Collection<String>>();

    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {/* w  w w.  j  av a2s  .co m*/

        SearchControls searchControls = new SearchControls();

        searchControls.setDerefLinkFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String filter = "objectClass=" + getLdapGroupClass();

        namingEnumeration = dirContext.search(getGroupsDn(), filter, searchControls);

        while (namingEnumeration.hasMore()) {
            SearchResult searchResult = namingEnumeration.next();

            String groupName = searchResult.getName();
            // cn=blabla we only want bla bla
            groupName = StringUtils.substringAfter(groupName, "=");

            Attribute uniqueMemberAttr = searchResult.getAttributes().get("uniquemember");

            if (uniqueMemberAttr != null) {
                NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr
                        .getAll();
                while (allMembersEnum.hasMore()) {
                    String userName = allMembersEnum.next();
                    // uid=blabla we only want bla bla
                    userName = StringUtils.substringAfter(userName, "=");
                    userName = StringUtils.substringBefore(userName, ",");
                    Collection<String> roles = usersWithRoles.get(userName);
                    if (roles == null) {
                        roles = new HashSet<String>();
                    }

                    roles.add(groupName);

                    usersWithRoles.put(userName, roles);

                }
            }

            log.debug("found groupName: '{}' with users: {}", groupName);

        }

        return usersWithRoles;
    } catch (NamingException e) {
        throw new LdapControllerException(e.getMessage(), e);
    }

    finally {

        if (namingEnumeration != null) {
            try {
                namingEnumeration.close();
            } catch (NamingException e) {
                log.warn("failed to close search results", e);
            }
        }
    }
}