在activedirectory中 支持 ldap 协议,我们可以在 java 中使用标准的 java jndi api 来访问它。ldap 服务器并非真的必须支持 jndi api,只要支持 ldap 协议就可以了。我们已经提供了一个简单的测试案例程序来认证一个 ldap 服务器的识别名。一般情况下,对待 activedirectory 不必与对待任何其他的 ldap 服务器有什么不同。
import java.util.properties; import javax.naming.*; import javax.naming.directory.*; //include the jndi in the classpath. you should use the same jdk used by websphere application server. class wasldapauth { public static void main(string[] args) { //***************** user information to be authenticated ******************************** //*****************please modify the following three properties accordingly ************ string ldaphost= "ldap://cliang1.austin.ibm.com:389"; //ldap host + port number string dn = "cn=user1, ou=austin,o=ibm,c=us"; // dn to be authenticated string password = "security"; // dns password //***************** end of user information properties props = new properties(); props.put(context.initial_context_factory, "com.sun.jndi.ldap.ldapctxfactory"); //for websphere 4.0 and 5.0 //props.put(context.initial_context_factory, "com.ibm.jndi.ldapctxfactory"); // for websphere 3.5 release props.put(context.security_authentication, "simple"); //use simple authentication mechanism props.put(context.security_credentials, password); props.put(context.security_principal, dn); props.put(context.provider_url, ldaphost); long start = system.currenttimemillis(); long end=0; long time =0; try { system.out.println("authenticating"); dircontext ctx = new initialdircontext(props); system.out.println("authenticated"); end = system.currenttimemillis(); time = end - start; system.out.println( "authentication takes = " + time + " millis"); system.out.println("successfully authenticate dn: "+dn); } catch (exception ex) { end = system.currenttimemillis(); time = end - start; system.out.println("exception is "+ex.tostring()); ex.printstacktrace(); system.out.println( "authentication takes = " + time + " millis"); system.out.println("fail to authenticate dn: "+dn); } } } |