Java access to Active Directory code

Source: Internet
Author: User
Tags ldap ldap search filter throw exception ad server

 Packagedemo;Importjava.util.Hashtable;ImportJavax.naming.Context;Importjavax.naming.NamingEnumeration;Importjavax.naming.NamingException;ImportJavax.naming.directory.Attribute;Importjavax.naming.directory.Attributes;ImportJavax.naming.directory.SearchControls;ImportJavax.naming.directory.SearchResult;ImportJavax.naming.ldap.InitialLdapContext;ImportJavax.naming.ldap.LdapContext; Public classAdopertest { Public voidGetadinfo (BooleanIsUser) {String host= "192.168.1.188";//Ad ServerString port = "389";//PortString URL =NewString ("ldap://" + Host + ":" +port); Hashtable hashenv=NewHashtable (); String AdminName= "[email protected]";//Note The user name: Domain\UserString AdminPassword = "2015";//PasswordHashenv.put (Context.security_authentication, "simple");//LDAP access security levelHashenv.put (Context.security_principal, AdminName);//AD UserHashenv.put (Context.security_credentials, AdminPassword);//AD Passwordhashenv.put (Context.initial_context_factory,"Com.sun.jndi.ldap.LdapCtxFactory");//LDAP Factory classhashenv.put (Context.provider_url, URL); Try{Ldapcontext CTX=NewInitialldapcontext (Hashenv,NULL); //domain nodeString searchbase = "ou= guangzhou daily Group, dc=gzrb,dc=local"; //LDAP search Filter classString searchfilter = IsUser? "(& (Objectclass=user))"                    : "(& (Objectclass=organizationalunit))"; //Search ControllerSearchcontrols Searchctls =NewSearchcontrols ();//Create the//Creating a search controllerSearchctls.setsearchscope (Searchcontrols.subtree_scope);//Specify//Customizing return Propertiesstring[] Returnedatts =NULL; if(isuser) {Returnedatts=NewString[] {"sAMAccountName",                        "DistinguishedName", "name" }; } Else{Returnedatts=NewString[] {"ou", "distinguishedname", "name" }; } searchctls.setreturningattributes (Returnedatts); //set the Return property set//Search LDAP based on domain node, filter class, and search controller set to get resultsNamingenumeration answer =Ctx.search (Searchbase, Searchfilter, SEARCHCTLS);//Search for objects using the filter             while(Answer.hasmoreelements ()) {//traversing result setsSearchResult sr = (SearchResult) answer.next ();//get the DN that matches the search criteriaString DN = sr.getattributes (). Get ("distinguishedname"). Get (). toString ();                SYSTEM.OUT.PRINTLN (DN); Attributes Attrs= Sr.getattributes ();//get an attribute set that matches a condition                if(Attrs! =NULL) {                    Try {                         for(Namingenumeration ne =attrs.getall (); ne. Hasmore ();) {Attribute Attr= (Attribute) ne.next ();//get the next attributeSystem.out.print ("Property name:" +Attr.getid (). toString ()); //Reading property values                             for(Namingenumeration e =Attr.getall (); E. hasmore ();) {String Val=E.next (). toString (); System.out.println ("Attribute value:" +val); }                        }                    } Catch(namingexception e) {System.err.println ("Throw Exception:" +e); }                }//if} ctx.close (); } Catch(namingexception e) {e.printstacktrace (); System.err.println ("Throw Exception:" +e); }    }     Public voidLogin () {String userName= "[email protected]";//User nameString Password = "2015";//PasswordString host = "192.168.1.188";//Ad ServerString port = "389";//PortString domain = "@hotent. Local";//the suffix name of the mailboxString URL =NewString ("ldap://" + Host + ":" +port); String User= Username.indexof (domain) > 0?Username:username+domain; Hashtable Env=NewHashtable (); Ldapcontext CTX=NULL; Env.put (Context.security_authentication,"Simple"); Env.put (context.security_principal, user); //without the mailbox suffix name, will be error, the specific reason has not been explored. Master can explain sharing. env.put (context.security_credentials, password); Env.put (Context.initial_context_factory,"Com.sun.jndi.ldap.LdapCtxFactory");        Env.put (Context.provider_url, URL); Try{CTX=NewInitialldapcontext (ENV,NULL);            Ctx.close (); System.out.println ("Verified success!"); } Catch(namingexception err) {err.printstacktrace (); System.out.println ("Validation failed!"); }    }     Public Static voidMain (String args[]) {//instantiation ofAdopertest AD =Newadopertest (); Ad. Getadinfo (true);//SYSTEM.OUT.PRINTLN ("---------organization---------");//AD. Getadinfo (false);Ad.login (); }}
This iterates the users, organizations, and logins in the system.

Java access to Active Directory code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.