How to connect to AD using JNDI

JNDI API sample for Active Directory

Sample code for authenticating to Active Directory by Using the JNDI
  1. SSL Authentication
       Hashtable env = new Hashtable();
       String adminName = "CN=,,,,,,DC=edu";
     //String adminName = "kkkk"; //using user principal name run much fast
       String adminPassword = "??XX??";
    
    
       env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
    
     //Access the truststore
       String keystore = "/PATH-TO/security/cacerts";
       System.setProperty("javax.net.ssl.trustStore",keystore);
    
     //set security credentials, note using simple cleartext authentication
       env.put(Context.SECURITY_AUTHENTICATION,"simple");
       env.put(Context.SECURITY_PRINCIPAL,adminName);
       env.put(Context.SECURITY_CREDENTIALS,adminPassword);
    
     //specify the use of SSL
       env.put(Context.SECURITY_PROTOCOL,"ssl");
    
     //connect to ou domain controller
       env.put(Context.PROVIDER_URL, "ldaps://ad.ohio.edu:636");
    
    
  2. DIGEST-MD5 Authentication,note using DIGEST-MD5 requires user account to be stored with reversible encryption
       Hashtable env = new Hashtable();
    
     //note only user principal name can be used
       String adminName = "jjjjj";
       String adminPassword = "??????";
       String ldapURL = "ldap://ad1.syslab.oit.ohio.edu:389";
    
       env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
    
     //set security credentials,
       env.put(Context.SECURITY_AUTHENTICATION,"DIGEST-MD5");
       env.put(Context.SECURITY_PRINCIPAL,adminName);
       env.put(Context.SECURITY_CREDENTIALS,adminPassword);
    
    //connect to my domain controller
      env.put(Context.PROVIDER_URL,ldapURL);
    
    
    
Sample codes for manage group and membership
  1. Create group
       String groupName = "jjjjjj";
    
       try{
         // Create the initial directory context
    	LdapContext ctx = new InitialLdapContext(env,null);
    
        // Create attributes to be associated with the new group
           Attributes attrs = new BasicAttributes(true);
    
           attrs.put("objectClass","group");
           attrs.put("samAccountName","jjjj");
           attrs.put("cn","jjj");
           attrs.put("description","jjjjjjjj");
    
         //group types
           int ADS_GROUP_TYPE_UNIVERSAL_GROUP = 0x0008;
           int ADS_GROUP_TYPE_SECURITY_ENABLED = 0x80000000;
    
           attrs.put("groupType",Integer.toString(ADS_GROUP_TYPE_UNIVERSAL_GROUP +ADS_GROUP_TYPE_SECURITY_ENABLED));
    
        // Create the context
           Context result = ctx.createSubcontext(groupName, attrs);
    
           ctx.close();
    
        }
        catch (NamingException e) {
    	    System.err.println("Problem creating group: " + e);
        }
    
  2. Delete Group
       String groupName = "CN=jjjjj";
    
       try {
          // Create the initial directory context
             LdapContext ctx = new InitialLdapContext(env,null);
    
             ctx.destroySubcontext(groupName);
    
             ctx.close();
       }
       catch (NamingException e) {
    	            System.err.println("Problem deleting group: " +e);
       }
    
  3. Add a member into a group
       String userName = "CN=jjjjj";
       String groupName = "CN=jjjjj";
    
       try {
          //Create the initial directory context
             InitialDirContext ctx = new InitialDirContext(env);
    
          //Create a LDAP add attribute for the member attribute
            ModificationItem mods[] = new ModificationItem[1];
    
            mods[0]= new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("member", userName));
    
          //update the group
           ctx.modifyAttributes(groupName,mods);
    
           ctx.close();
       }
       catch (NamingException e) {
    	  System.err.println("Problem adding member: " + e);
       }
    
  4. Delete a member from a group
       String userName = "CN=jjjjj";
       String groupName = "CN=jjjjj";
    
       try {
        // Create the initial directory context
           InitialDirContext ctx = new InitialDirContext(env);
    
         //Create a LDAP add attribute for the member attribute
           ModificationItem mods[] = new ModificationItem[1];
           mods[0]= new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute("member", userName));
    
         //update the group
           ctx.modifyAttributes(groupName,mods);
    
           ctx.close();
    
       }
       catch (NamingException e) {
    	System.err.println("Problem deleting member: " + e);
       }
    
  5. retrieve Members from a group
       try {
         //Create the initial directory context
           LdapContext ctx = new InitialLdapContext(env,null);
    
        //Create the search controls
          SearchControls searchCtls = new SearchControls();
    
        //Specify the search scope
          searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    
        //specify the LDAP search filter
          String searchFilter = "(&(objectClass=group)(CN=Peoples))";
    
        //Specify the Base for the search
          String searchBase = "dc=jjjjj";
    
        //initialize counter to total the group members
          int totalResults = 0;
    
        //Specify the attributes to return
          String returnedAtts[]={"member"};
          searchCtls.setReturningAttributes(returnedAtts);
    
        //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();
    
    	     System.out.println(">>>" + sr.getName());
    
    	   //Print out the members
    
    	     Attributes attrs = sr.getAttributes();
    	     if (attrs != null) {
                    try {
    		    for (NamingEnumeration ae = attrs.getAll();ae.hasMore();) {
    		        Attribute attr = (Attribute)ae.next();
    			System.out.println("Attribute: " + attr.getID());
    			for (NamingEnumeration e = attr.getAll();e.hasMore();totalResults++) {
    			      System.out.println(" " +  totalResults + ". " +  e.next());
    			}
                	    }
     	       }
    	       catch (NamingException e)	{
    		    System.err.println("Problem listing members: " + e);
    	       }
    	     }
    	}
    	    System.out.println("Total members: " + totalResults);
    	    ctx.close();
    
         }
         catch (NamingException e) {
    	    System.err.println("Problem searching directory: " + e);
         }
    
Comments