Example usage for javax.naming.directory DirContext search

List of usage examples for javax.naming.directory DirContext search

Introduction

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

Prototype

public NamingEnumeration<SearchResult> search(String name, String filterExpr, Object[] filterArgs,
        SearchControls cons) throws NamingException;

Source Link

Document

Searches in the named context or object for entries that satisfy the given search filter.

Usage

From source file:Compare.java

public static void main(String[] args) {

    // Set up environment for creating initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

    try {/* ww  w .  j a  v  a 2  s.  c  o  m*/
        // Create initial context
        DirContext ctx = new InitialDirContext(env);

        // Value of attribute
        byte[] key = { (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66,
                (byte) 0x67 };

        // Set up search controls
        SearchControls ctls = new SearchControls();
        ctls.setReturningAttributes(new String[0]); // return no attrs
        ctls.setSearchScope(SearchControls.OBJECT_SCOPE); // search object only

        // Invoke search method that will use the LDAP "compare" operation
        NamingEnumeration answer = ctx.search("cn=S. User, ou=NewHires", "(mySpecialKey={0})",
                new Object[] { key }, ctls);

        // Print the answer
        // FilterArgs.printSearchEnumeration(answer);

        // Close the context when we're done
        ctx.close();
    } catch (NamingException e) {
        e.printStackTrace();
    }
}

From source file:SearchWithFilterObjs.java

public static void main(String[] args) {

    // Set up the environment for creating the initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

    try {//from   w  w w  .  j  a  v a 2 s  .  co m
        // Create initial context
        DirContext ctx = new InitialDirContext(env);

        // Specify the ids of the attributes to return
        String[] attrIDs = { "sn", "telephonenumber", "golfhandicap", "mail" };
        SearchControls ctls = new SearchControls();
        ctls.setReturningAttributes(attrIDs);

        // Specify the search filter to match
        // Ask for objects with attribute sn == Geisel and which have
        // the "mail" attribute.
        String filter = "(&(sn={0})(mail=*))";

        // Search for objects using filter
        NamingEnumeration answer = ctx.search("ou=People", filter, new Object[] { "Geisel" }, ctls);

        // Print the answer
        // Search.printSearchEnumeration(answer);

        // Close the context when we're done
        ctx.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.archone.ad.authentication.ShoadRealm.java

private String getUserDn(String username) throws javax.naming.NamingException {
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    DirContext dirContext = contextSource.getReadOnlyContext();
    NamingEnumeration<SearchResult> searchResults = dirContext.search("",
            adConfiguration.getUserDnSearchFilter(), new String[] { username }, controls);

    SearchResult sr = searchResults.next();

    if (sr == null || searchResults.hasMore()) {
        throw new AuthenticationException();
    }/*  w w  w  .j a va2s .  c o  m*/

    return sr.getNameInNamespace();
}

From source file:edu.lafayette.metadb.model.userman.UserManDAO.java

/**
 * Get the LDAP DN for a user./*from   w  w  w .j a va2s  .c  om*/
 * @param searchUser
 * @param searchPassword
 * @param userName
 * @return
 */
@SuppressWarnings("unchecked")
private static String getDN(String searchUser, String searchPassword, String userName) {
    // The resultant DN
    String result;

    // Set up environment for creating initial context
    Hashtable env = new Hashtable(11);
    env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(javax.naming.Context.PROVIDER_URL, Global.LDAP_URL);

    // Use admin credencials for search// Authenticate
    env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "Simple");
    env.put(javax.naming.Context.SECURITY_PRINCIPAL, searchUser);
    env.put(javax.naming.Context.SECURITY_CREDENTIALS, searchPassword);

    DirContext ctx = null;
    try {
        // Create initial context
        ctx = new InitialDirContext(env);
        //MetaDbHelper.note("Created LDAP context");

        Attributes matchAttrs = new BasicAttributes(true);
        matchAttrs.put(new BasicAttribute(Global.LDAP_ID, userName));
        //MetaDbHelper.note("Created attributes");

        // look up attributes
        try {
            //MetaDbHelper.note("Setting up query");

            SearchControls ctrls = new SearchControls();
            ctrls.setSearchScope(Global.LDAP_SCOPE);

            NamingEnumeration<SearchResult> answer = ctx.search(Global.LDAP_URL + Global.LDAP_CONTEXT,
                    "(&({0}={1}))", new Object[] { Global.LDAP_ID, userName }, ctrls);

            //MetaDbHelper.note("NamingEnumeration retrieved");

            while (answer.hasMoreElements()) {
                SearchResult sr = answer.next();
                if (StringUtils.isEmpty(Global.LDAP_CONTEXT)) {
                    result = sr.getName();
                } else {
                    result = (sr.getName() + "," + Global.LDAP_CONTEXT);
                }

                //MetaDbHelper.note("Got DN: "+result);

                return result;
            }
        } catch (NamingException e) {
            MetaDbHelper.logEvent(e);
            //MetaDbHelper.note("LDAP Error: Failed Search");
        }
    } catch (NamingException e) {
        MetaDbHelper.logEvent(e);
        //MetaDbHelper.note("LDAP Error: Failed authentication");
    } finally {
        // Close the context when we're done
        try {
            if (ctx != null)
                ctx.close();
        } catch (NamingException e) {
        }
    }
    // No DN match found
    return null;
}

From source file:org.archone.ad.domain.UserHelper.java

public List<String> lookupMembershipGroups(DirContext dirContext, String userDn)
        throws javax.naming.NamingException {

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

    NamingEnumeration<SearchResult> searchResults = dirContext.search("",
            adConfiguration.getMembershipSearchFilter(), new String[] { userDn }, controls);

    List<String> roles = new LinkedList<String>();
    while (searchResults.hasMore()) {
        GroupDn groupDn = new GroupDn(searchResults.next().getNameInNamespace(),
                adConfiguration.getGroupsRdn());
        roles.add(groupDn.getAsGroupId());
    }//from www .ja  v  a 2  s  . com

    return roles;
}

From source file:ldap.SearchUtility.java

public boolean userHasAttribute(String DN, String attrType, String attrValue, DirContext context)
        throws NamingException {
    Attributes atts = new BasicAttributes();
    atts.put(attrType, attrValue);//from   w w w  .  jav  a2s  .  co m
    NamingEnumeration<SearchResult> userResults = context.search(new LdapName(DN), "(" + attrType + "={0})",
            new String[] { attrValue }, getSearchControls());
    return (userResults.hasMore());
}

From source file:ru.efo.security.ADUserDetailsService.java

private ADUserDetails loadUserByUsername(DirContext context, String username, String password)
        throws UsernameNotFoundException {
    try {/*ww w  .  j a v a2 s.c o m*/
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // search for username
        NamingEnumeration<SearchResult> renum = context.search(userSearchBase,
                "(&(objectClass=user)(sAMAccountName={0}))", new Object[] { username }, controls);
        if (!renum.hasMoreElements()) {
            throw new UsernameNotFoundException("User '" + username + "' is not exist");
        }
        SearchResult result = renum.next();
        final Attributes attributes = result.getAttributes();

        // User's display name
        String displayName = null;
        Attribute attr = attributes.get(displayNameAttribute);
        if (attr != null) {
            displayName = attr.get().toString();
        }
        if (!StringUtils.hasText(displayName))
            displayName = username;
        logger.log(Level.FINE, "Display name: " + displayName);

        // User's email
        String email = null;
        attr = attributes.get(emailAttribute);
        if (attr != null) {
            email = attr.get().toString();
        }
        logger.log(Level.FINE, "E-mail: " + email);

        // User's phone number
        String phone = null;
        attr = attributes.get(phoneAttribute);
        if (attr != null) {
            phone = attr.get().toString();
        }
        logger.log(Level.FINE, "Phone: " + phone);

        // Is user blocked
        boolean blocked = false;
        attr = attributes.get("userAccountControl");
        if (attr != null) {
            blocked = (Long.parseLong(attr.get().toString()) & 2) != 0;
        }
        logger.log(Level.FINE, "Blocked: " + blocked);

        // describe roles and groups
        final Set<String> roles = new TreeSet<>();
        final Set<String> groups = new TreeSet<>();
        Attribute memberOf = attributes.get("memberOf");
        describeRoles(context, memberOf, groups, roles);

        // Describe user primary role
        Attribute attrPrimaryGroupId = attributes.get("primaryGroupId");
        Attribute attrObjectSid = attributes.get("objectSid");
        if (attrPrimaryGroupId != null && attrObjectSid != null) {
            int primaryGroupId = Integer.parseInt(attrPrimaryGroupId.get().toString());
            byte[] objectSid = (byte[]) attrObjectSid.get();
            // add primary group RID
            for (int i = 0; i < 4; i++) {
                objectSid[objectSid.length - 4 + i] = (byte) (primaryGroupId & 0xFF);
                primaryGroupId >>= 8;
            }
            StringBuilder tmp = new StringBuilder();
            for (int i = 2; i <= 7; i++) {
                tmp.append(Integer.toHexString(objectSid[i] & 0xFF));
            }
            // convert objectSid to String
            StringBuilder sidBuilder = new StringBuilder("S-").append(objectSid[0]).append("-")
                    .append(Long.parseLong(tmp.toString(), 16));
            // the sub authorities count
            int count = objectSid[1];
            // add authorities
            for (int i = 0; i < count; i++) {
                tmp.setLength(0);

                int offset = i * 4;
                tmp.append(String.format("%02X%02X%02X%02X", (objectSid[11 + offset] & 0xFF),
                        (objectSid[10 + offset] & 0xFF), (objectSid[9 + offset] & 0xFF),
                        (objectSid[8 + offset] & 0xFF)));
                sidBuilder.append('-').append(Long.parseLong(tmp.toString(), 16));
            }
            SearchControls searchControls = new SearchControls();
            searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            renum = context.search(userSearchBase, "(&(objectClass=group)(objectSid={0}))",
                    new Object[] { sidBuilder.toString() }, searchControls);
            if (renum.hasMoreElements()) {
                result = renum.next();
                attr = result.getAttributes().get("distinguishedName");
                describeRoles(context, attr, groups, roles);
            }
        }
        return new ADUserDetails(username, password, displayName, email, phone, blocked, groups, roles);
    } catch (NamingException ex) {
        logger.log(Level.SEVERE, "Could not find user '" + username + "'", ex);
        throw new UsernameNotFoundException(ex.getMessage());
    }
}

From source file:ldap.SearchUtility.java

/**
 * This returns a list of all users that match the particular attribute value.
 * Often this will be a single user, in which case the list will only contain one value.  If
 * you know this is the case, use the 'getUser()' form of this method instead.
 * @param attrType//from   ww  w .java  2 s  . com
 * @param attrValue
 * @return
 * @throws NamingException
 */
public List<Entry> getUsers(String attrType, String attrValue, DirContext context) throws NamingException {
    logger.info("getUsers(attrType,attrValue,context)");
    List<Entry> users = new ArrayList<Entry>();
    Attributes atts = new BasicAttributes();
    atts.put(attrType, attrValue);
    //NamingEnumeration<SearchResult> userResults = context.search(new LdapName(Config.SEARCH_BASE_DN), attrType + "={0}", new String[] {attrValue}, getSearchControls());
    NamingEnumeration<SearchResult> userResults = context.search(new LdapName(LdapConstants.ldapSearchBaseDn),
            attrType + "={0}", new String[] { attrValue }, getSearchControls());
    while (userResults.hasMore()) {
        SearchResult userResult = userResults.next();
        users.add(new Entry(userResult));
    }
    return users;
}

From source file:ldap.SearchUtility.java

public boolean checkPassword(String DN, String pwdAtt, String value, DirContext context)
        throws NamingException, UnsupportedEncodingException {
    SearchControls ctls = new SearchControls();
    ctls.setReturningAttributes(new String[0]); // Return no attrs
    ctls.setSearchScope(SearchControls.OBJECT_SCOPE); // Search object only
    //byte[] pwdBytes = value.getBytes("UTF-8");
    byte[] pwdBytes = value.getBytes(LdapConstants.UTF8);

    // Invoke search method that will use the LDAP "compare" operation
    NamingEnumeration answer = context.search(DN, "(" + pwdAtt + "={0})", new Object[] { pwdBytes }, ctls);
    return answer.hasMore();
}

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(//from   w w  w .j a  v a2 s  .co  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;
}