Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package beans;
- import java.util.*;
- import javax.naming.*;
- import javax.naming.directory.*;
- public class TestLdapScript {
- public static void main(String[] args) {
- String userName = "username";
- String passWord = "password";
- try { Hashtable env = new Hashtable();
- env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
- env.put(Context.PROVIDER_URL,"LDAP://xx.xxx.net:389"); //replace with your server URL/IP
- //only DIGEST-MD5 works with our Windows Active Directory
- env.put(Context.SECURITY_AUTHENTICATION,"DIGEST-MD5"); //No other SALS worked with me
- env.put(Context.SECURITY_PRINCIPAL,userName); // specify the username ONLY to let Microsoft Happy
- env.put(Context.SECURITY_CREDENTIALS, passWord); //the password
- DirContext ctx = new InitialDirContext(env);
- //Create the search controls
- SearchControls searchCtls = new SearchControls();
- //Specify the attributes to return
- String returnedAtts[]={"cn","DisplayName"};
- searchCtls.setReturningAttributes(returnedAtts);
- //Specify the search scope
- searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
- //specify the LDAP search filter
- //String searchFilter = "(&(ObjectClass=Person)(!(ObjectClass=user)))";
- //String searchFilter = "(&(objectClass=user)(&(objectClass=Person)(!(userAccountControl=514))))";
- String searchFilter = "(&(objectClass=person)(CN=))";
- //Specify the Base for the search
- String searchBase = "DC=xxxx,DC=net";
- //initialize counter to total the results
- int totalResults = 0;
- // Search for objects using the filter
- NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);
- //Loop through the search results
- while (answer.hasMoreElements()) {
- SearchResult sr = (SearchResult)answer.next();
- totalResults++;
- System.out.println(">>>" + sr.getName());
- // Print out some of the attributes, catch the exception if the attributes have no values
- Attributes attrs = sr.getAttributes();
- if (attrs != null) {
- try {
- System.out.println(" surname: " + attrs.get("cn").get());
- System.out.println(" firstname: " + attrs.get("DisplayName").get());
- }
- catch (NullPointerException e) {
- System.out.println("Errors listing attributes: " + e);
- }
- }
- }
- ctx.close();
- } catch(NamingException ne)
- { System.out.println("Error authenticating user:");
- System.out.println(ne.getMessage());
- return;
- } //if no exception, the user is already authenticated.
- System.out.println("OK, successfully authenticating user");
- }
- }
Add Comment
Please, Sign In to add comment