java 调用ActiveDirectory,使用标准的LDAP协议
类别: JAVA教程
在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\"; // DN\'s 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); }}} |
- 上一篇: JAVA/JSP学习系列之一(JDK安装)-
- 下一篇: java编写TCP方式的通信程序
-= 资 源 教 程 =-
文 章 搜 索