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:org.apache.zeppelin.rest.GetUserList.java

/**
 * function to extract users from LDAP/*from   w  w w  .  j av  a2  s.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:fi.koku.services.utility.authorization.impl.GroupServiceLDAPImpl.java

private List<LdapPerson> getPersonDnsByPics(List<String> pics) {
    SearchControls ctrl = new SearchControls();
    ctrl.setReturningAttributes(new String[] { "uid" });
    ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String q = getPersonsQuery(pics);
    logger.debug("getPersonDnsByPics: query: " + q.toString());
    List<LdapPerson> persons = ldapTemplate.search("", q, ctrl, new LdapPersonMapper(),
            new DirContextProcessorNoop());
    logger.debug("persons: " + persons.size());
    return persons;
}

From source file:sk.lazyman.gizmo.security.SimpleBindAunthenticator.java

@Override
public DirContextOperations authenticate(Authentication authentication) {
    DirContextOperations user = null;//from   www . j  av a 2 s .  c  o m
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            "Can only process UsernamePasswordAuthenticationToken objects");

    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    if (StringUtils.isEmpty(password)) {
        LOG.debug("Rejecting empty password for user " + username);
        throw new BadCredentialsException(
                messages.getMessage("BindAuthenticator.emptyPassword", "Empty Password"));
    }

    // If DN patterns are configured, try authenticating with them directly
    for (String dn : getUserDns(username)) {
        user = bindWithDn(dn, username, password);

        if (user != null) {
            break;
        }
    }

    // Otherwise use the configured search object to find the user and authenticate with the returned DN.
    if (user == null && getUserSearch() != null) {
        DirContextOperations userFromSearch = getUserSearch().searchForUser(username);
        user = bindWithDn(userFromSearch.getDn().toString(), username, password);
    }

    try {
        if (user != null && StringUtils.isNotEmpty(gizmoGroup)) {
            BaseLdapPathContextSource ctxSource = (BaseLdapPathContextSource) getContextSource();
            DirContext ctx = ctxSource.getReadOnlyContext();

            DistinguishedName userDn = new DistinguishedName(user.getDn());
            userDn.prepend(ctxSource.getBaseLdapPath());

            SearchControls controls = new SearchControls();
            controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            String filter = String.format(GROUP_SEARCH_QUERY, gizmoGroup, userDn.toCompactString());
            NamingEnumeration en = ctx.search("", filter, controls);
            if (!en.hasMore()) {
                throw new BadCredentialsException(
                        messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials"));
            }
        }
    } catch (javax.naming.NamingException ex) {
        throw new BadCredentialsException("Couldn't check group membership");
    }

    if (user == null) {
        throw new BadCredentialsException(
                messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials"));
    }

    return user;
}

From source file:io.apiman.tools.ldap.ApimanLdapServer.java

@Test
public void startLdapServer() throws Exception {
    DirContext ctx = createContext();
    Assert.assertNotNull(ctx);//from  www.  j  a  va  2 s . co  m

    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration<SearchResult> result = ctx.search("o=apiman", "(ObjectClass=*)", controls);

    int count = 0;
    while (result.hasMore()) {
        result.next();
        count++;
    }

    String url = "ldap://" + LDAP_SERVER + ":" + ldapServer.getPort();
    System.out.println("======================================================");
    System.out.println("LDAP server started successfully.");
    System.out.println("");
    System.out.println("  URL: " + url);
    System.out.println("  Node Count: " + count);
    System.out.println("  Direct Bind DN: cn=${username},ou=developers,ou=people,o=apiman");
    System.out.println("======================================================");
    System.out.println("");
    System.out.println("");
    System.out.println("Press Enter to stop the LDAP server.");
    new BufferedReader(new InputStreamReader(System.in)).readLine();
    System.out.println("Shutting down the LDAP server...");
}

From source file:com.hs.mail.security.login.JndiLoginModule.java

@SuppressWarnings("unchecked")
protected boolean authenticate(String username, String password) throws Exception {
    DirContext context = null;//from  w w  w. j  av  a  2 s .c  o m
    try {
        context = open();
        searchFilterFormat.format(new String[] { username });
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(subtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE);
        if (returnAttribute != null) {
            String[] attribs = StringUtils.split(returnAttribute, ",");
            constraints.setReturningAttributes(attribs);
        }
        NamingEnumeration ne = context.search(base, searchFilter, constraints);
        if (ne == null || !ne.hasMore()) {
            return false;
        }
        SearchResult sr = (SearchResult) ne.next();
        if (ne.hasMore()) {
            // Ignore for now
        }
        // Check the credentials by binding to server
        if (bindUser(context, sr.getNameInNamespace(), password)) {
            return true;
        } else {
            return true;
        }
    } catch (NamingException e) {
        close(context);
        return false;
    }
}

From source file:org.springframework.ldap.samples.article.dao.TraditionalPersonDaoImpl.java

public List getAllPersonNames() {
    DirContext ctx = createAnonymousContext();

    LinkedList list = new LinkedList();
    NamingEnumeration results = null;
    try {// www .  j  ava  2  s .  c o  m
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        results = ctx.search("", "(objectclass=person)", controls);

        while (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            Attributes attributes = searchResult.getAttributes();
            Attribute attr = attributes.get("cn");
            String cn = (String) attr.get();
            list.add(cn);
        }
    } catch (NamingException e) {
        throw new RuntimeException(e);
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }
    return list;
}

From source file:org.springframework.ldap.demo.dao.PersonDaoImpl.java

public List<String> getAllPersonNames() {
    DirContext ctx = createAnonymousContext();

    LinkedList<String> list = new LinkedList<String>();
    NamingEnumeration<?> results = null;
    try {/*w  w  w  .j  a v a2 s .c om*/
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        results = ctx.search("", "(objectclass=person)", controls);

        while (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            Attributes attributes = searchResult.getAttributes();
            Attribute attr = attributes.get("cn");
            String cn = (String) attr.get();
            list.add(cn);
        }
    } catch (NamingException e) {
        throw new RuntimeException(e);
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }
    return list;
}

From source file:org.apache.cxf.sts.claims.LdapUtils.java

public static Name getDnOfEntry(LdapTemplate ldapTemplate, String baseDN, String objectClass,
        String filterAttributeName, String filterAttributeValue) {

    ContextMapper mapper = new AbstractContextMapper() {
        public Object doMapFromContext(DirContextOperations ctx) {
            return ctx.getDn();
        }//w w w  .  j a  v a2s .  co  m
    };

    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectclass", objectClass))
            .and(new EqualsFilter(filterAttributeName, filterAttributeValue));

    List<?> result = ldapTemplate.search((baseDN == null) ? "" : baseDN, filter.toString(),
            SearchControls.SUBTREE_SCOPE, mapper);

    if (result != null && result.size() > 0) {
        //not only the first one....
        return (Name) result.get(0);
    }
    return null;
}

From source file:org.ballerinalang.auth.ldap.nativeimpl.GetLdapScopesOfUser.java

private String[] getLDAPGroupsListOfUser(String userName, List<String> searchBase,
        CommonLdapConfiguration ldapAuthConfig) throws UserStoreException, NamingException {
    if (userName == null) {
        throw new BallerinaException("userName value is null.");
    }/*  w w  w  .  j  a  va2s. co m*/

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    // Load normal roles with the user
    String searchFilter = ldapAuthConfig.getGroupNameListFilter();
    String roleNameProperty = ldapAuthConfig.getGroupNameAttribute();
    String membershipProperty = ldapAuthConfig.getMembershipAttribute();
    String nameInSpace = this.getNameInSpaceForUserName(userName, ldapConfiguration);

    if (membershipProperty == null || membershipProperty.length() < 1) {
        throw new BallerinaException("membershipAttribute not set in configuration");
    }

    String membershipValue;
    if (nameInSpace != null) {
        LdapName ldn = new LdapName(nameInSpace);
        if (LdapConstants.MEMBER_UID.equals(ldapAuthConfig.getMembershipAttribute())) {
            // membership value of posixGroup is not DN of the user
            List rdns = ldn.getRdns();
            membershipValue = ((Rdn) rdns.get(rdns.size() - 1)).getValue().toString();
        } else {
            membershipValue = escapeLdapNameForFilter(ldn);
        }
    } else {
        return new String[0];
    }

    searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + "))";
    String returnedAtts[] = { roleNameProperty };
    searchCtls.setReturningAttributes(returnedAtts);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Reading roles with the membershipProperty Property: " + membershipProperty);
    }

    List<String> list = this.getListOfNames(searchBase, searchFilter, searchCtls, roleNameProperty, false);
    return list.toArray(new String[list.size()]);
}

From source file:org.wso2.carbon.appfactory.userstore.internal.OTLDAPUtil.java

public static NamingEnumeration<SearchResult> searchForUser(String searchFilter, String[] returnedAtts,
        DirContext dirContext, String userSearchBase) throws UserStoreException {
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    if (returnedAtts != null && returnedAtts.length > 0) {
        searchCtls.setReturningAttributes(returnedAtts);
    }//from   ww w  .j a  va  2 s .c om
    try {
        return dirContext.search(userSearchBase, searchFilter, searchCtls);
    } catch (NamingException e) {
        log.error("Search failed.", e);
        throw new UserStoreException(e.getMessage());
    }
}