Example usage for javax.naming.directory SearchControls setSearchScope

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

Introduction

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

Prototype

public void setSearchScope(int scope) 

Source Link

Document

Sets the search scope to one of: OBJECT_SCOPE, ONELEVEL_SCOPE, SUBTREE_SCOPE.

Usage

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

/**
 * return the user dn of an ldap entry//from w  w  w  .  java  2s .  com
 * 
 * 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;
    }
}

From source file:org.apache.manifoldcf.authorities.authorities.sharepoint.SharePointADAuthority.java

/** Obtain the DistinguishedName for a given user logon name.
*@param ctx is the ldap context to use.//from w  w w .ja va  2  s .  co m
*@param userName (Domain Logon Name) is the user name or identifier.
*@param searchBase (Full Domain Name for the search ie: DC=qa-ad-76,DC=metacarta,DC=com)
*@return DistinguishedName for given domain user logon name. 
* (Should throws an exception if user is not found.)
*/
protected String getDistinguishedName(LdapContext ctx, String userName, String searchBase,
        String userACLsUsername) throws ManifoldCFException {
    String returnedAtts[] = { "distinguishedName" };
    String searchFilter = "(&(objectClass=user)(" + userACLsUsername + "=" + userName + "))";
    SearchControls searchCtls = new SearchControls();
    searchCtls.setReturningAttributes(returnedAtts);
    //Specify the search scope  
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchCtls.setReturningAttributes(returnedAtts);

    try {
        NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);
        while (answer.hasMoreElements()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();
            if (attrs != null) {
                String dn = attrs.get("distinguishedName").get().toString();
                return dn;
            }
        }
        return null;
    } catch (NamingException e) {
        throw new ManifoldCFException(e.getMessage(), e);
    }
}

From source file:org.apache.manifoldcf.authorities.authorities.sharepoint.SharePointADAuthority.java

/** Get the AD-derived access tokens for a user and domain */
protected List<String> getADTokens(String userPart, String domainPart, String userName)
        throws NameNotFoundException, NamingException, ManifoldCFException {
    // Now, look through the rules for the matching domain controller
    String domainController = null;
    for (DCRule rule : dCRules) {
        String suffix = rule.getSuffix();
        if (suffix.length() == 0
                || domainPart.toLowerCase(Locale.ROOT).endsWith(suffix.toLowerCase(Locale.ROOT))
                        && (suffix.length() == domainPart.length()
                                || domainPart.charAt((domainPart.length() - suffix.length()) - 1) == '.')) {
            domainController = rule.getDomainControllerName();
            break;
        }/*  w  ww.j  av  a2 s. c  om*/
    }

    if (domainController == null)
        // No AD user
        return null;

    // Look up connection parameters
    DCConnectionParameters dcParams = dCConnectionParameters.get(domainController);
    if (dcParams == null)
        // No AD user
        return null;

    // Use the complete fqn if the field is the "userPrincipalName"
    String userBase;
    String userACLsUsername = dcParams.getUserACLsUsername();
    if (userACLsUsername != null && userACLsUsername.equals("userPrincipalName")) {
        userBase = userName;
    } else {
        userBase = userPart;
    }

    //Build the DN searchBase from domain part
    StringBuilder domainsb = new StringBuilder();
    int j = 0;
    while (true) {
        if (j > 0)
            domainsb.append(",");

        int k = domainPart.indexOf(".", j);
        if (k == -1) {
            domainsb.append("DC=").append(ldapEscape(domainPart.substring(j)));
            break;
        }
        domainsb.append("DC=").append(ldapEscape(domainPart.substring(j, k)));
        j = k + 1;
    }

    // Establish a session with the selected domain controller
    LdapContext ctx = createDCSession(domainController);

    //Get DistinguishedName (for this method we are using DomainPart as a searchBase ie: DC=qa-ad-76,DC=metacarta,DC=com")
    String searchBase = getDistinguishedName(ctx, userBase, domainsb.toString(), userACLsUsername);
    if (searchBase == null)
        return null;

    //specify the LDAP search filter
    String searchFilter = "(objectClass=user)";

    //Create the search controls for finding the access tokens   
    SearchControls searchCtls = new SearchControls();

    //Specify the search scope, must be base level search for tokenGroups
    searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE);

    //Specify the attributes to return
    String returnedAtts[] = { "tokenGroups", "objectSid" };
    searchCtls.setReturningAttributes(returnedAtts);

    //Search for tokens.  Since every user *must* have a SID, the "no user" detection should be safe.
    NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);

    List<String> theGroups = new ArrayList<String>();
    String userToken = userTokenFromLoginName(domainPart + "\\" + userPart);
    if (userToken != null)
        theGroups.add(userToken);

    //Loop through the search results
    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();

        //the sr.GetName should be null, as it is relative to the base object

        Attributes attrs = sr.getAttributes();
        if (attrs != null) {
            try {
                for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
                    Attribute attr = (Attribute) ae.next();
                    for (NamingEnumeration e = attr.getAll(); e.hasMore();) {
                        String sid = sid2String((byte[]) e.next());
                        String token = attr.getID().equals("objectSid") ? userTokenFromSID(sid)
                                : groupTokenFromSID(sid);
                        theGroups.add(token);
                    }
                }
            } catch (NamingException e) {
                throw new ManifoldCFException(e.getMessage(), e);
            }
        }
    }

    if (theGroups.size() == 0)
        return null;

    // User is in AD, so add the 'everyone' group
    theGroups.add(everyoneGroup());
    return theGroups;
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

@SuppressWarnings("unchecked")
private SearchResult findUser(String username) throws NamingException, LoginException {
    SearchControls ctls = new SearchControls();
    ctls.setCountLimit(1);/*  ww  w  .j ava 2 s  . c o m*/
    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = OBJECT_CLASS_FILTER;

    debug("Searching for users with filter: \'" + filter + "\'" + " from base dn: " + _userBaseDn);

    Object[] filterArguments = new Object[] { _userObjectClass, _userIdAttribute, username };
    NamingEnumeration results = _rootContext.search(_userBaseDn, filter, filterArguments, ctls);

    debug("Found user?: " + results.hasMoreElements());

    if (!results.hasMoreElements()) {
        throw new LoginException("User not found.");
    }

    return (SearchResult) results.nextElement();
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

private ConcurrentHashMap<String, List<String>> buildRoleMemberOfMap(DirContext dirContext) {
    Object[] filterArguments = { _roleObjectClass };
    SearchControls ctls = new SearchControls();
    ctls.setDerefLinkFlag(true);//from   w w  w .  j  av  a2 s. co  m
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    ConcurrentHashMap<String, List<String>> roleMemberOfMap = new ConcurrentHashMap<String, List<String>>();

    try {
        NamingEnumeration<SearchResult> results = dirContext.search(_roleBaseDn, _roleMemberFilter, ctls);
        while (results.hasMoreElements()) {
            SearchResult result = results.nextElement();
            Attributes attributes = result.getAttributes();

            if (attributes == null) {
                continue;
            }

            Attribute roleAttribute = attributes.get(_roleNameAttribute);
            Attribute memberAttribute = attributes.get(_roleMemberAttribute);

            if (roleAttribute == null || memberAttribute == null) {
                continue;
            }

            NamingEnumeration role = roleAttribute.getAll();
            NamingEnumeration members = memberAttribute.getAll();

            if (!role.hasMore() || !members.hasMore()) {
                continue;
            }

            String roleName = (String) role.next();
            if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) {
                roleName = roleName.replace(_rolePrefix, "");
            }

            while (members.hasMore()) {
                String member = (String) members.next();
                Matcher roleMatcher = rolePattern.matcher(member);
                if (!roleMatcher.find()) {
                    continue;
                }
                String roleMember = roleMatcher.group(1);
                List<String> memberOf;
                if (roleMemberOfMap.containsKey(roleMember)) {
                    memberOf = roleMemberOfMap.get(roleMember);
                } else {
                    memberOf = new ArrayList<String>();
                }

                memberOf.add(roleName);

                roleMemberOfMap.put(roleMember, memberOf);
            }

        }
    } catch (NamingException e) {
        e.printStackTrace();
    }
    return roleMemberOfMap;
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

/**
 * attempts to get the users credentials from the users context
 * <p/>/*from  w ww  .jav  a2  s  .  c  o  m*/
 * NOTE: this is not an user authenticated operation
 *
 * @param username
 * @return
 * @throws LoginException
 */
@SuppressWarnings("unchecked")
private String getUserCredentials(String username) throws LoginException {
    String ldapCredential = null;

    SearchControls ctls = new SearchControls();
    ctls.setCountLimit(1);
    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    try {
        Object[] filterArguments = { _userObjectClass, _userIdAttribute, username };
        NamingEnumeration results = _rootContext.search(_userBaseDn, OBJECT_CLASS_FILTER, filterArguments,
                ctls);

        debug("Found user?: " + results.hasMoreElements());

        if (!results.hasMoreElements()) {
            throw new LoginException("User not found.");
        }

        SearchResult result = findUser(username);

        Attributes attributes = result.getAttributes();

        setDemographicAttributes(attributes);
        Attribute attribute = attributes.get(_userPasswordAttribute);
        if (attribute != null) {
            try {
                byte[] value = (byte[]) attribute.get();

                ldapCredential = new String(value);
            } catch (NamingException e) {
                LOG.info("no password available under attribute: " + _userPasswordAttribute);
            }
        }
    } catch (NamingException e) {
        throw new LoginException("Root context binding failure.");
    }

    debug("user cred is present: " + (ldapCredential != null));

    return ldapCredential;
}

From source file:edu.internet2.middleware.psp.ldap.LdapSpmlTarget.java

/** {@inheritDoc} */
public void execute(LookupRequest lookupRequest, LookupResponse lookupResponse) {

    Ldap ldap = null;// ww  w.j  a va 2  s.c  o  m
    try {
        // will not return AD Range option attrs
        // Attributes attributes = ldap.getAttributes(escapedDn, retAttrs);

        SearchFilter sf = new SearchFilter();
        sf.setFilter("objectclass=*");
        SearchControls sc = new SearchControls();
        sc.setSearchScope(SearchControls.OBJECT_SCOPE);

        // This lookup requests attributes defined for *all* objects.
        // Perhaps there should be two searches, one for the identifier
        // and a second for attributes.
        String[] retAttrs = getPSP().getNames(getId(), lookupRequest.getReturnData()).toArray(new String[] {});
        sc.setReturningAttributes(retAttrs);

        // TODO logging
        String dn = lookupRequest.getPsoID().getID();
        String escapedDn = LdapSpmlTarget.escapeForwardSlash(dn);

        ldap = ldapPool.checkOut();

        LOG.debug("Target '{}' - Searching '{}'", getId(), PSPUtil.toString(lookupRequest));
        Iterator<SearchResult> searchResults = ldap.search(escapedDn, sf, sc);
        LOG.debug("Target '{}' - Searched '{}'", getId(), PSPUtil.toString(lookupRequest));

        if (!searchResults.hasNext()) {
            fail(lookupResponse, ErrorCode.NO_SUCH_IDENTIFIER);
            return;
        }

        SearchResult result = searchResults.next();

        if (searchResults.hasNext()) {
            fail(lookupResponse, ErrorCode.CUSTOM_ERROR, "More than one result found.");
            return;
        }
        Attributes attributes = result.getAttributes();

        // return attributes in order defined by config
        OrderedLdapBeanFactory orderedLdapBeanFactory = new OrderedLdapBeanFactory();
        // sort values
        SortedLdapBeanFactory sortedLdapBeanFactory = new SortedLdapBeanFactory();

        LdapAttributes ldapAttributes = orderedLdapBeanFactory.newLdapAttributes();
        for (String retAttr : retAttrs) {
            Attribute attr = attributes.get(retAttr);
            if (attr != null) {
                LdapAttribute ldapAttribute = sortedLdapBeanFactory.newLdapAttribute();
                ldapAttribute.setAttribute(attr);
                ldapAttributes.addAttribute(ldapAttribute);
            }
        }

        LdapEntry entry = sortedLdapBeanFactory.newLdapEntry();
        entry.setDn(dn);
        entry.setLdapAttributes(ldapAttributes);

        if (this.isLogLdif()) {
            LdapResult lr = sortedLdapBeanFactory.newLdapResult();
            lr.addEntry(entry);
            LdifResultConverter lrc = new LdifResultConverter();
            LOG.info("Target '{}' - LDIF\n{}", getId(), lrc.toLdif(lr));
        }

        // build pso
        lookupResponse.setPso(getPSO(entry, lookupRequest.getReturnData()));

    } catch (NameNotFoundException e) {
        fail(lookupResponse, ErrorCode.NO_SUCH_IDENTIFIER);
    } catch (LdapPoolException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (InvalidNameException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (NamingException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (DSMLProfileException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (Spml2Exception e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (PspException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } finally {
        if (ldap != null) {
            ldapPool.checkIn(ldap);
        }
    }
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

@SuppressWarnings("unchecked")
private List getUserRolesByDn(DirContext dirContext, String userDn, String username)
        throws LoginException, NamingException {
    List<String> roleList = new ArrayList<String>();

    if (dirContext == null || _roleBaseDn == null
            || (_roleMemberAttribute == null && _roleUsernameMemberAttribute == null)
            || _roleObjectClass == null) {
        LOG.warn(//ww w.j a  va 2  s.c o  m
                "JettyCachingLdapLoginModule: No user roles found: roleBaseDn, roleObjectClass and roleMemberAttribute or roleUsernameMemberAttribute must be specified.");
        addSupplementalRoles(roleList);
        return roleList;
    }

    String[] attrIDs = { _roleNameAttribute };
    SearchControls ctls = new SearchControls();
    ctls.setReturningAttributes(attrIDs);
    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = OBJECT_CLASS_FILTER;
    final NamingEnumeration results;

    if (null != _roleUsernameMemberAttribute) {
        Object[] filterArguments = { _roleObjectClass, _roleUsernameMemberAttribute, username };
        results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls);
    } else {
        Object[] filterArguments = { _roleObjectClass, _roleMemberAttribute, userDn };
        results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls);
    }

    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()) {
            if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) {
                String role = (String) roles.next();
                roleList.add(role.replace(_rolePrefix, ""));
            } else {
                roleList.add((String) roles.next());
            }
        }
    }

    addSupplementalRoles(roleList);

    if (_nestedGroups) {
        roleList = getNestedRoles(dirContext, roleList);
    }

    if (roleList.size() < 1) {
        LOG.warn("JettyCachingLdapLoginModule: User '" + username
                + "' has no role membership; role query configuration may be incorrect");
    } else {
        debug("JettyCachingLdapLoginModule: User '" + username + "' has roles: " + roleList);
    }

    return roleList;
}

From source file:edu.internet2.middleware.psp.ldap.LdapSpmlTarget.java

/** {@inheritDoc} */
public void execute(SearchRequest searchRequest, SearchResponse searchResponse) {

    // query/*  w w  w .  j av  a 2 s.  c o m*/
    Query query = searchRequest.getQuery();

    // query filter
    // TODO support QueryClause other than our own
    String filter = null;
    for (QueryClause queryClause : query.getQueryClauses()) {
        if (queryClause instanceof HasReference) {
            HasReference hasReference = (HasReference) queryClause;
            if (hasReference.getTypeOfReference() != null && hasReference.getToPsoID() != null
                    && hasReference.getToPsoID().getID() != null) {
                filter = "(" + hasReference.getTypeOfReference() + "=" + hasReference.getToPsoID().getID()
                        + ")";
                // TODO what do we do with hasReference.getReferenceData(); ?
            }
        } else if (queryClause instanceof Filter) {
            FilterItem filterItem = ((Filter) queryClause).getItem();
            if (filterItem instanceof EqualityMatch) {
                String name = ((EqualityMatch) filterItem).getName();
                String value = ((EqualityMatch) filterItem).getValue().getValue();
                filter = "(" + name + "=" + value + ")";
            }
        } else {
            fail(searchResponse, ErrorCode.MALFORMED_REQUEST, "Unsupported query.");
            return;
        }
    }
    if (DatatypeHelper.isEmpty(filter)) {
        fail(searchResponse, ErrorCode.MALFORMED_REQUEST, "A filter is required.");
        return;
    }

    // query base
    if (query.getBasePsoID() == null || query.getBasePsoID().getID() == null) {
        fail(searchResponse, ErrorCode.MALFORMED_REQUEST, "A basePsoID is required.");
        return;
    }
    String base = query.getBasePsoID().getID();

    SearchControls searchControls = new SearchControls();

    // query scope
    Scope scope = query.getScope();
    if (scope != null) {
        searchControls.setSearchScope(PSPUtil.getScope(scope));
    }

    ReturnData returnData = searchRequest.getReturnData();
    if (returnData == null) {
        returnData = ReturnData.EVERYTHING;
    }

    // attributes to return
    String[] retAttrs = getPSP().getNames(getId(), returnData).toArray(new String[] {});
    searchControls.setReturningAttributes(retAttrs);

    Ldap ldap = null;
    try {
        ldap = ldapPool.checkOut();

        LOG.debug("Target '{}' - Search will return attributes '{}'", getId(), Arrays.asList(retAttrs));
        LOG.debug("Target '{}' - Searching '{}'", getId(), PSPUtil.toString(searchRequest));
        Iterator<SearchResult> searchResults = ldap.search(base, new SearchFilter(filter), searchControls);
        LOG.debug("Target '{}' - Searched '{}'", getId(), PSPUtil.toString(searchRequest));

        SortedLdapBeanFactory ldapBeanFactory = new SortedLdapBeanFactory();
        LdapResult ldapResult = ldapBeanFactory.newLdapResult();
        ldapResult.addEntries(searchResults);

        Collection<LdapEntry> entries = ldapResult.getEntries();
        LOG.debug("Target '{}' - Search found {} entries.", getId(), entries.size());
        for (LdapEntry entry : entries) {
            searchResponse.addPSO(getPSO(entry, returnData));
        }

        if (logLdif) {
            Ldif ldif = new Ldif();
            LOG.info("Target '{}' - LDIF\n{}", getId(), ldif.createLdif(ldapResult));
        }

    } catch (NameNotFoundException e) {
        fail(searchResponse, ErrorCode.NO_SUCH_IDENTIFIER, e);
    } catch (NamingException e) {
        fail(searchResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (LdapPoolException e) {
        fail(searchResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (Spml2Exception e) {
        fail(searchResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (PspException e) {
        fail(searchResponse, ErrorCode.CUSTOM_ERROR, e);
    } finally {
        ldapPool.checkIn(ldap);
    }

}

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java

protected Function<InitialDirContext, NamingEnumeration<SearchResult>> buildUserSearcher(final String query) {
    LOGGER.debug("Building user searcher for query {}", query);

    final SearchControls userSearchCtls = new SearchControls();
    userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    userSearchCtls.setReturningAttributes(this.userKeys.getFirst());
    // MNT-14001 fix, set search limit to ensure that server will not return more search results then provided by paged result control
    userSearchCtls.setCountLimit(this.queryBatchSize > 0 ? this.queryBatchSize : 0);

    return (ctx) -> {
        try {//www.j a  va 2  s  .  c  o m
            final NamingEnumeration<SearchResult> results = ctx.search(this.userSearchBase, query,
                    userSearchCtls);
            return results;
        } catch (final NamingException e) {
            throw new AlfrescoRuntimeException("Failed to import people.", e);
        }
    };
}