Example usage for javax.naming.ldap LdapContext search

List of usage examples for javax.naming.ldap LdapContext search

Introduction

In this page you can find the example usage for javax.naming.ldap LdapContext search.

Prototype

public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes,
        String[] attributesToReturn) throws NamingException;

Source Link

Document

Searches in a single context for objects that contain a specified set of attributes, and retrieves selected attributes.

Usage

From source file:org.apache.zeppelin.realm.LdapRealm.java

boolean isUserMemberOfDynamicGroup(LdapName userLdapDn, String memberUrl,
        final LdapContextFactory ldapContextFactory) throws NamingException {
    // ldap://host:port/dn?attributes?scope?filter?extensions
    if (memberUrl == null) {
        return false;
    }/*from  www .  j  a v  a2s  .  co  m*/
    String[] tokens = memberUrl.split("\\?");
    if (tokens.length < 4) {
        return false;
    }

    String searchBaseString = tokens[0].substring(tokens[0].lastIndexOf("/") + 1);
    String searchScope = tokens[2];
    String searchFilter = tokens[3];

    LdapName searchBaseDn = new LdapName(searchBaseString);

    // do scope test
    if (searchScope.equalsIgnoreCase("base")) {
        log.debug("DynamicGroup SearchScope base");
        return false;
    }
    if (!userLdapDn.toString().endsWith(searchBaseDn.toString())) {
        return false;
    }
    if (searchScope.equalsIgnoreCase("one") && (userLdapDn.size() != searchBaseDn.size() - 1)) {
        log.debug("DynamicGroup SearchScope one");
        return false;
    }
    // search for the filter, substituting base with userDn
    // search for base_dn=userDn, scope=base, filter=filter
    LdapContext systemLdapCtx = null;
    systemLdapCtx = ldapContextFactory.getSystemLdapContext();
    boolean member = false;
    NamingEnumeration<SearchResult> searchResultEnum = null;
    try {
        searchResultEnum = systemLdapCtx.search(userLdapDn, searchFilter,
                searchScope.equalsIgnoreCase("sub") ? SUBTREE_SCOPE : ONELEVEL_SCOPE);
        if (searchResultEnum.hasMore()) {
            return true;
        }
    } finally {
        try {
            if (searchResultEnum != null) {
                searchResultEnum.close();
            }
        } finally {
            LdapUtils.closeContext(systemLdapCtx);
        }
    }
    return member;
}

From source file:org.apache.zeppelin.realm.LdapRealm.java

/**
* Returns the LDAP User Distinguished Name (DN) to use when acquiring an
* {@link javax.naming.ldap.LdapContext LdapContext} from the
* {@link LdapContextFactory}.//from   w ww  .j a va2 s  .  com
* <p/>
* If the the {@link #getUserDnTemplate() userDnTemplate} property has been
* set, this implementation will construct the User DN by substituting the
* specified {@code principal} into the configured template. If the
* {@link #getUserDnTemplate() userDnTemplate} has not been set, the method
* argument will be returned directly (indicating that the submitted
* authentication token principal <em>is</em> the User DN).
*
* @param principal
*            the principal to substitute into the configured
*            {@link #getUserDnTemplate() userDnTemplate}.
* @return the constructed User DN to use at runtime when acquiring an
*         {@link javax.naming.ldap.LdapContext}.
* @throws IllegalArgumentException
*             if the method argument is null or empty
* @throws IllegalStateException
*             if the {@link #getUserDnTemplate userDnTemplate} has not been
*             set.
* @see LdapContextFactory#getLdapContext(Object, Object)
*/
@Override
protected String getUserDn(final String principal) throws IllegalArgumentException, IllegalStateException {
    String userDn;
    String matchedPrincipal = matchPrincipal(principal);
    String userSearchBase = getUserSearchBase();
    String userSearchAttributeName = getUserSearchAttributeName();

    // If not searching use the userDnTemplate and return.
    if ((userSearchBase == null || userSearchBase.isEmpty()) || (userSearchAttributeName == null
            && userSearchFilter == null && !"object".equalsIgnoreCase(userSearchScope))) {
        userDn = expandTemplate(userDnTemplate, matchedPrincipal);
        if (log.isDebugEnabled()) {
            log.debug("LDAP UserDN and Principal: " + userDn + "," + principal);
        }
        return userDn;
    }

    // Create the searchBase and searchFilter from config.
    String searchBase = expandTemplate(getUserSearchBase(), matchedPrincipal);
    String searchFilter = null;
    if (userSearchFilter == null) {
        if (userSearchAttributeName == null) {
            searchFilter = String.format("(objectclass=%1$s)", getUserObjectClass());
        } else {
            searchFilter = String.format("(&(objectclass=%1$s)(%2$s=%3$s))", getUserObjectClass(),
                    userSearchAttributeName,
                    expandTemplate(getUserSearchAttributeTemplate(), matchedPrincipal));
        }
    } else {
        searchFilter = expandTemplate(userSearchFilter, matchedPrincipal);
    }
    SearchControls searchControls = getUserSearchControls();

    // Search for userDn and return.
    LdapContext systemLdapCtx = null;
    NamingEnumeration<SearchResult> searchResultEnum = null;
    try {
        systemLdapCtx = getContextFactory().getSystemLdapContext();
        if (log.isDebugEnabled()) {
            log.debug("SearchBase,SearchFilter,UserSearchScope: " + searchBase + "," + searchFilter + ","
                    + userSearchScope);
        }
        searchResultEnum = systemLdapCtx.search(searchBase, searchFilter, searchControls);
        // SearchResults contains all the entries in search scope
        if (searchResultEnum.hasMore()) {
            SearchResult searchResult = searchResultEnum.next();
            userDn = searchResult.getNameInNamespace();
            if (log.isDebugEnabled()) {
                log.debug("UserDN Returned,Principal: " + userDn + "," + principal);
            }
            return userDn;
        } else {
            throw new IllegalArgumentException("Illegal principal name: " + principal);
        }
    } catch (AuthenticationException ne) {
        ne.printStackTrace();
        throw new IllegalArgumentException("Illegal principal name: " + principal);
    } catch (NamingException ne) {
        throw new IllegalArgumentException("Hit NamingException: " + ne.getMessage());
    } finally {
        try {
            if (searchResultEnum != null) {
                searchResultEnum.close();
            }
        } catch (NamingException ne) {
            // Ignore exception on close.
        } finally {
            LdapUtils.closeContext(systemLdapCtx);
        }
    }
}

From source file:org.apache.zeppelin.rest.GetUserList.java

/**
 * function to extract users from LDAP/*from w  w w  .j  a  v a2s .c o m*/
 */
public List<String> getUserList(JndiLdapRealm r, String searchText) {
    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 {
        LdapContext ctx = CF.getSystemLdapContext();
        SearchControls constraints = new SearchControls();
        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) {
        LOG.error("Error retrieving User list from Ldap Realm", e);
    }
    LOG.info("UserList: " + userList);
    return userList;
}

From source file:org.apache.zeppelin.rest.GetUserList.java

/**
 * function to extract users from Zeppelin LdapRealm
 *//*from w ww . j ava 2 s  . co m*/
public List<String> getUserList(LdapRealm r, String searchText) {
    List<String> userList = new ArrayList<>();
    if (LOG.isDebugEnabled()) {
        LOG.debug("SearchText: " + searchText);
    }
    String userAttribute = r.getUserSearchAttributeName();
    String userSearchRealm = r.getUserSearchBase();
    String userObjectClass = r.getUserObjectClass();
    JndiLdapContextFactory CF = (JndiLdapContextFactory) r.getContextFactory();
    try {
        LdapContext ctx = CF.getSystemLdapContext();
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attrIDs = { userAttribute };
        constraints.setReturningAttributes(attrIDs);
        NamingEnumeration result = ctx.search(userSearchRealm,
                "(&(objectclass=" + userObjectClass + ")(" + userAttribute + "=" + searchText + "))",
                constraints);
        while (result.hasMore()) {
            Attributes attrs = ((SearchResult) result.next()).getAttributes();
            if (attrs.get(userAttribute) != null) {
                String currentUser;
                if (r.getUserLowerCase()) {
                    LOG.debug("userLowerCase true");
                    currentUser = ((String) attrs.get(userAttribute).get()).toLowerCase();
                } else {
                    LOG.debug("userLowerCase false");
                    currentUser = (String) attrs.get(userAttribute).get();
                }
                if (LOG.isDebugEnabled()) {
                    LOG.debug("CurrentUser: " + currentUser);
                }
                userList.add(currentUser.trim());
            }
        }
    } catch (Exception e) {
        LOG.error("Error retrieving User list from Ldap Realm", e);
    }
    return userList;
}

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 ww w .ja v  a 2  s  .  c  o m
        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.zeppelin.service.ShiroAuthenticationService.java

/** Function to extract users from Zeppelin LdapRealm. */
private List<String> getUserList(LdapRealm r, String searchText, int numUsersToFetch) {
    List<String> userList = new ArrayList<>();
    LOGGER.debug("SearchText: " + searchText);
    String userAttribute = r.getUserSearchAttributeName();
    String userSearchRealm = r.getUserSearchBase();
    String userObjectClass = r.getUserObjectClass();
    JndiLdapContextFactory cf = (JndiLdapContextFactory) r.getContextFactory();
    try {//from   w w w  .j a v a2s . c o  m
        LdapContext ctx = cf.getSystemLdapContext();
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        constraints.setCountLimit(numUsersToFetch);
        String[] attrIDs = { userAttribute };
        constraints.setReturningAttributes(attrIDs);
        NamingEnumeration result = ctx.search(userSearchRealm,
                "(&(objectclass=" + userObjectClass + ")(" + userAttribute + "=*" + searchText + "*))",
                constraints);
        while (result.hasMore()) {
            Attributes attrs = ((SearchResult) result.next()).getAttributes();
            if (attrs.get(userAttribute) != null) {
                String currentUser;
                if (r.getUserLowerCase()) {
                    LOGGER.debug("userLowerCase true");
                    currentUser = ((String) attrs.get(userAttribute).get()).toLowerCase();
                } else {
                    LOGGER.debug("userLowerCase false");
                    currentUser = (String) attrs.get(userAttribute).get();
                }
                LOGGER.debug("CurrentUser: " + currentUser);
                userList.add(currentUser.trim());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error retrieving User list from Ldap Realm", e);
    }
    return userList;
}

From source file:org.eclipse.skalli.core.user.ldap.LDAPClient.java

private User searchUserById(LdapContext ldap, String userId) throws NamingException {
    SearchControls sc = getSearchControls();
    NamingEnumeration<SearchResult> results = null;
    try {// w  w  w  .j  a  v  a  2 s . c o m
        results = ldap.search(config.getBaseDN(),
                MessageFormat.format("(&(objectClass=user)(sAMAccountName={0}))", userId), sc); //$NON-NLS-1$
        while (results != null && results.hasMore()) {
            SearchResult entry = results.next();
            User user = processEntry(entry);
            if (user != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug(MessageFormat.format("Success reading from LDAP: {0}, {1} <{2}>", //$NON-NLS-1$
                            user.getUserId(), user.getDisplayName(), user.getEmail()));
                }
                return user;
            }
        }
    } finally {
        closeQuietly(results);
    }
    return new User(userId);
}

From source file:org.eclipse.skalli.core.user.ldap.LDAPClient.java

private List<User> searchUserByName(LdapContext ldap, String name) throws NamingException {
    List<User> ret = new ArrayList<User>(0);
    try {//from   w  ww.j a  v  a  2s  .  c  o  m
        boolean somethingAdded = false;
        SearchControls sc = getSearchControls();
        String[] parts = StringUtils.split(NormalizeUtil.normalize(name), " ,"); //$NON-NLS-1$
        if (parts.length == 1) {
            somethingAdded = search(parts[0], ret, ldap, sc);
        } else if (parts.length > 1) {
            // givenname surname ('Michael Ochmann'), or surname givenname('Ochmann, Michael')
            NamingEnumeration<SearchResult> results = null;
            try {
                results = ldap.search(config.getBaseDN(),
                        MessageFormat.format("(&(objectClass=user)(givenName={0}*)(sn={1}*))", //$NON-NLS-1$
                                parts[0], parts[1]),
                        sc);
                somethingAdded |= addLDAPSearchResult(ret, results);
            } finally {
                closeQuietly(results);
            }
            try {
                results = ldap.search(config.getBaseDN(),
                        MessageFormat.format("(&(objectClass=user)(sn={0}*)(givenName={1}*))", //$NON-NLS-1$
                                parts[0], parts[1]),
                        sc);
                somethingAdded |= addLDAPSearchResult(ret, results);
            } finally {
                closeQuietly(results);
            }
            // givenname initial surname, e.g. 'Michael R. Ochmann'
            if (parts.length > 2) {
                try {
                    results = ldap.search(config.getBaseDN(),
                            MessageFormat.format("(&(objectClass=user)(givenName={0}*)(sn={1}*))", //$NON-NLS-1$
                                    parts[0], parts[2]),
                            sc);
                    somethingAdded |= addLDAPSearchResult(ret, results);
                } finally {
                    closeQuietly(results);
                }
                try {
                    results = ldap.search(config.getBaseDN(),
                            MessageFormat.format("(&(objectClass=user)(sn={0}*)(givenName={1}*))", //$NON-NLS-1$
                                    parts[0], parts[2]),
                            sc);
                    somethingAdded |= addLDAPSearchResult(ret, results);
                } finally {
                    closeQuietly(results);
                }
            }
            if (!somethingAdded) {
                // try to match each part individually
                for (int i = 0; i < parts.length; ++i) {
                    somethingAdded = search(parts[i], ret, ldap, sc);
                }
            }
        }
    } catch (SizeLimitExceededException e) {
        // 1000 is good enough at the moment for this use case...
        LOG.warn(MessageFormat.format("LDAP query size limit exceeded while searching for ''{0}''", name), e);
    }
    return ret;
}

From source file:org.eclipse.skalli.core.user.ldap.LDAPClient.java

private boolean search(String s, List<User> ret, LdapContext ldap, SearchControls sc) throws NamingException {
    // try a match with surname*
    boolean somethingAdded = false;
    NamingEnumeration<SearchResult> results = null;
    try {/*from w ww .  ja v a  2 s . co m*/
        results = ldap.search(config.getBaseDN(),
                MessageFormat.format("(&(objectClass=user)(|(sn={0}*)(givenName={1}*)))", s, s), sc); //$NON-NLS-1$
        somethingAdded = addLDAPSearchResult(ret, results);
    } finally {
        closeQuietly(results);
    }
    if (!somethingAdded) {
        try {
            // try a match with the account name and mail address
            results = ldap.search(config.getBaseDN(),
                    MessageFormat.format("(&(objectClass=user)(sAMAccountName={0}*))", s), sc); //$NON-NLS-1$
            somethingAdded |= addLDAPSearchResult(ret, results);
        } finally {
            closeQuietly(results);
        }
        if (!somethingAdded) {
            try {
                // try to match surname~= or givenname~=
                results = ldap.search(config.getBaseDN(),
                        MessageFormat.format("(&(objectClass=user)(|(sn~={0})(givenName~={1})))", s, s), sc); //$NON-NLS-1$
                somethingAdded |= addLDAPSearchResult(ret, results);
            } finally {
                closeQuietly(results);
            }
            if (!somethingAdded) {
                try {
                    results = ldap.search(config.getBaseDN(),
                            MessageFormat.format("(&(objectClass=user)(mail={0}*))", s), sc); //$NON-NLS-1$
                    somethingAdded |= addLDAPSearchResult(ret, results);
                } finally {
                    closeQuietly(results);
                }
            }
        }
    }
    return somethingAdded;
}

From source file:org.jsecurity.realm.activedirectory.ActiveDirectoryRealm.java

private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException {
    Set<String> roleNames;
    roleNames = new LinkedHashSet<String>();

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

    String userPrincipalName = username;
    if (principalSuffix != null) {
        userPrincipalName += principalSuffix;
    }//from  ww w  .j a v  a  2s. com

    String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))";

    NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, 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;
}